Get the next array item using the key 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];
}
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.
<?php
$users_emails = array(
'Spence' => 'spence@someplace.com',
'Matt' => 'matt@someplace.com',
'Marc' => 'marc@someplace.com',
'Adam' => 'adam@someplace.com',
'Paul' => 'paul@someplace.com');
$current = 'Paul';
$keys = array_keys($users_emails);
$ordinal = (array_search($current,$keys)+1)%count($keys);
$next = $keys[$ordinal];
echo $next;
?>
You can use next(); function, if you want to just get next coming element of array.
<?php
$transport = array('foot', 'bike', 'car', 'plane');
$mode = current($transport); // $mode = 'foot';
$mode = next($transport); // $mode = 'bike';
$mode = next($transport); // $mode = 'car';
$mode = prev($transport); // $mode = 'bike';
$mode = end($transport); // $mode = 'plane';
?>
Update
and if you want to check and use that next element exist you can try :
Create a function :
function has_next($array) {
if (is_array($array)) {
if (next($array) === false) {
return false;
} else {
return true;
}
} else {
return false;
}
}
Call it :
if (has_next($array)) {
echo next($array);
}
Source : php.net
$array = array("sony"=>"xperia", "apple"=>"iphone", 1 , 2, 3, 4, 5, 6 );
foreach($array as $key=>$val)
{
$curent = $val;
if (!isset ($next))
$next = current($array);
else
$next = next($array);
echo (" $curent | $next <br>");
}
You can print like this :-
foreach(YourArr as $key => $val)
{ echo next(YourArr[$key]);
prev(YourArr); }
精彩评论