Reputation: 1145
Suppose I have an array like below
[0] => 25
[1] => 30
[2] => 35
[3] => 40
[4] => 45
[5] => 50
[6] => 55
[7] => 60
[8] => 65
[9] => 70
If i input my key as 4 , I need to get nearest 2 arrays , example
[2] => 35
[3] => 40
[4] => 45
[5] => 50
[6] => 55
right now I use something like below.
$key = 4;
$count = 2;
$slice = array_slice($array,$key-$count,4+($count-1));
But if my $key is 1 and count is 2, I need something like
[0] => 25
[1] => 30
[2] => 35
[3] => 40
and if key is 8 I need
[6] => 55
[7] => 60
[8] => 65
[9] => 70
I cannot achieve this slice code above , so some one guide some other way , thank you.
Upvotes: 1
Views: 59
Reputation: 3476
Below Code satisfy your test cases
$array = array(
'0' => 25,
'1' => 30,
'2' => 35,
'3' => 40,
'4' => 45,
'5' => 50,
'6' => 55,
'7' => 60,
'8' => 65,
'9' => 70,
);
$key = 8;
$count = 2;
$slice = array_slice(
$array,
( ( $key - $count ) > 0 ) ? ( $key - $count) : 0 ,
( ( $key - $count ) > 0 ) ? ( (2 * $count) + 1 ) : ( (2 * $count) + ( $key - $count + 1 ) )
);
Here is the online demo
Upvotes: 1
Reputation: 41810
Setting the offset to $key - $count
is correct. You can use max()
to keep it from going negative.
$offset = max(0, $key - $count);
For the length, the basic calculation is 2 * $count + 1
. By adding min($key - $count, 0)
to that, you can subtract any of the left-side count that would extend below zero.
$length = 2 * $count + 1 + min($key - $count, 0);
You don't need to worry if the slice extends beyond the count of the array, that part will be ignored.
$slice = array_slice($array, $offset, $length);
Upvotes: 1
Reputation: 11
Erwin's answer is correct.
If you also want to ensure the same number of values are selected if a key at the end of the array is given you will need to check for this:
$key = 4;
$count = 2;
if ( ($key - $count) < 0){
$key = $count;
} elseif ( ($key + $count) > count($array) ) {
$key = count($array) - $count;
}
$slice = array_slice($array,$key-$count,$key+($count-1));
Upvotes: 0
Reputation: 2408
You probably mean:
$slice = array_slice($array,$key-$count,**$key**+($count-1));
Just make sure you don't go negative:
$key = 4;
$count = 2;
if ( ($key - $count) < 0){
$key = $count;
}
$slice = array_slice($array,$key-$count,$key+($count-1));
Upvotes: 0