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];
}
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.
The array_keys() function returns an array containing the keys.
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' ).
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).
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.
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