There is an array:

Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15) 

You need a beautiful function that will return:

  • With parameter 8 - Array Array(6, 7, 8, 9, 10) ,
  • With parameter 12 - Array Array(10, 11, 12, 13, 15) ,
  • With parameter 1 - Array Array(1, 2, 3, 4, 5) ,
  • With parameter 2 - Array Array(1, 2, 3, 4, 5) ,
  • With parameter 15 - Array Array(11, 12, 13, 14, 15) ,
  • With parameter 14 - Array Array(11, 12, 13, 14, 15)

Closed due to the fact that the essence of the issue is incomprehensible by the participants Alexey Shimansky , Vladimir Martyanov , iksuy , Dmitriy Simushev , Vadim Ovchinnikov January 19, 17 at 10:43 .

Try to write more detailed questions. To get an answer, explain what exactly you see the problem, how to reproduce it, what you want to get as a result, etc. Give an example that clearly demonstrates the problem. If the question can be reformulated according to the rules set out in the certificate , edit it .

  • one
    What have you tried to do and what have you failed? - Moonvvell
  • sort by modulus difference and take the first 5 items. - teran

1 answer 1

um

 function returnClosest($array, $position, $offset = 2){ $position--; if(($position + $offset * 2 + 1) > count($array)){ $position = count($array) - ($offset + 1);//10 - 2 } return array_slice($array, $position - $offset, $offset * 2 + 1); } $arr = array(1,2,3,4,5,6,7,8,9,0); var_dump(returnClosest($arr, 10)); var_dump(returnClosest($arr, 5)); var_dump(returnClosest($arr, 1)); //Получаем результаты, приведенные ниже 

array(5) ( 6, 7, 8, 9, 0 )
array(5) ( 3, 4, 5, 6, 7 )
array(5) ( 1, 2, 3, 4, 5 )