Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get keys before and after specific value in array (in PHP)

Tags:

php

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).

like image 649
Paul Avatar asked Oct 19 '22 11:10

Paul


1 Answers

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

like image 99
RomanPerekhrest Avatar answered Nov 15 '22 06:11

RomanPerekhrest