php - How to find array next value based on current value

282

I have array as below-

Array
(
   [1] => admin
   [5d1acff7-51f5-d10a-8807-5ce3a25f3f01] => atul
   [9324e078-e651-09ab-856c-5d00cf1d6302] => tushar
   [3e4d9711-e4e0-f9de-8d40-5d021f3137fb] => praful
   [b283b589-c527-389f-498b-5cf0ea2338e1] => suraj

)

Here I cant find the next value based on key,so I want to find next value based on current value. Suppose I have current value is 'atul' now I want next value as 'tushar' with its key.

26

Answer

Solution:

Get the offset of the search string, increment it, then access the key and value from the isolated element.

Checking for a{-code-1} boolean result fromarray_search() is critical. Otherwise incrementing{-code-1} becomes1, and then you have an incorrect script.

Code: (Demo) (or var_export the element)

$array = [
   1 => 'admin',
   '5d1acff7-51f5-d10a-8807-5ce3a25f3f01' => 'atul',
   '9324e078-e651-09ab-856c-5d00cf1d6302' => 'tushar',
   '3e4d9711-e4e0-f9de-8d40-5d021f3137fb' => 'praful',
   'b283b589-c527-389f-498b-5cf0ea2338e1' => 'suraj'
];

$values = array_values($array);
$offset = array_search('atul', $values);

if ($offset !== {-code-1} && isset($values[++$offset])) {
    $element = array_slice($array, $offset, 1, true);
    echo key($element) , " : " , current($element);
} else {
    echo "not found or no next";
}

Output:

9324e078-e651-09ab-856c-5d00cf1d6302 : tushar

People are also looking for solutions to the problem: php - Change the week start day from Monday to Saturday

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.