简体   繁体   中英

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.

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>");
}
<?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 print like this :-

foreach(YourArr as $key => $val)
{  echo next(YourArr[$key]); 
  prev(YourArr); }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM