5

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

1
  • What is the condition for selecting that very number after the specific value is set to 1? Commented Apr 19, 2016 at 12:34

3 Answers 3

8

Solution using array_search function:

$array = [441, 212, 314, 406];
$val = 441;

$currentKey = array_search($val, $array);

//Check for possible bool value returned by array_search
//Check for possible random index values

if(!is_bool($currentKey) & array_is_list($array)) {
  $before = $array[$currentKey ? $currentKey-1 : count($array)-1];
  $after = $array[($currentKey != count($array)-1) ? $currentKey+1 : key($array)];
}

var_dump($before, $after);

The output:

int(406)
int(212)

http://php.net/manual/en/function.array-search.php

Sign up to request clarification or add additional context in comments.

Comments

-2
$key = array_search ('441', $arr);
$beforeKey = $key-1;
if($beforeKey<1)
{ $beforeKey = count($array)-1; }
$afterKey = $key+1;
$beforeValue = $array[$beforeKey];
$afterValue = $array[$afterKey];

Comments

-2

for recursive keys after a search may want something like this:

function get_all_after_array_key($array,$key){
    $currentKey = array_search($key, array_keys($array));
    $hasNextKey = (isset($array[$currentKey + 1])) ? TRUE : FALSE;
    $array = array_keys($array);
    $after = [];
    do {
        if(isset($array[$currentKey + 1])) {
            $hasNextKey = TRUE;
            $after[] = $array[$currentKey + 1];
            $currentKey = $currentKey + 1;
        } else {
            $hasNextKey = FALSE;
        }
    } while($hasNextKey == TRUE);
    return $after;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.