I want to get the value before and after a specific value of an array in PHP.
For example I have:
$array = (441, 212, 314, 406);
And my $specific_value is 441.
In this example I should get the before (406) and after (212).
If my value is 212 I should be get the before (441) and after (314).
Solution using array_search function:
$array = [441, 212, 314, 406];
$val = 441;
$currentKey = array_search($val, $array);
$before = isset($array[$currentKey - 1]) ? $array[$currentKey - 1] : $array[count($array) - 1];
$after = isset($array[$currentKey + 1]) ? $array[$currentKey + 1] : $array[0];
var_dump($before, $after);
The output:
int(406)
int(212)
http://php.net/manual/en/function.array-search.php
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With