Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the next array item using the key php

Tags:

php

I have an array

Array(1=>'test',9=>'test2',16=>'test3'... and so on);

how do I get the next array item by passing the key.

for example if i have key 9 then I should get test3 as result. if i have 1 then it should return 'test2' as result.

Edited to make it More clear

echo  somefunction($array,9); //result should be 'test3'
function somefunction($array,$key)
{
  return $array[$dont know what to use];
}
like image 271
Daric Avatar asked Jun 20 '11 06:06

Daric


People also ask

How do you find the next value in an array?

The next() function moves the internal pointer to, and outputs, the next element in the array. Related methods: prev() - moves the internal pointer to, and outputs, the previous element in the array. current() - returns the value of the current element in an array.

What is array_keys () used for in PHP?

The array_keys() function returns an array containing the keys.

How get key from value in array in PHP?

If you have a value and want to find the key, use array_search() like this: $arr = array ('first' => 'a', 'second' => 'b', ); $key = array_search ('a', $arr); $key will now contain the key for value 'a' (that is, 'first' ).

What does Array_splice () function do give an example?

The array_splice() function removes selected elements from an array and replaces it with new elements. The function also returns an array with the removed elements. Tip: If the function does not remove any elements (length=0), the replaced array will be inserted from the position of the start parameter (See Example 2).


1 Answers

function get_next($array, $key) {
   $currentKey = key($array);
   while ($currentKey !== null && $currentKey != $key) {
       next($array);
       $currentKey = key($array);
   }
   return next($array);
}

Or:

return current(array_slice($array, array_search($key, array_keys($array)) + 1, 1));

It is hard to return the correct result with the second method if the searched for key doesn't exist. Use with caution.

like image 85
deceze Avatar answered Sep 24 '22 08:09

deceze