Daric
Daric

Reputation: 16769

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];
}

Upvotes: 22

Views: 37381

Answers (5)

Rushil K. Pachchigar
Rushil K. Pachchigar

Reputation: 1321

<?php
$users_emails = array(
'Spence' => '[email protected]', 
'Matt'   => '[email protected]', 
'Marc'   => '[email protected]', 
'Adam'   => '[email protected]', 
'Paul'   => '[email protected]');

$current = 'Paul';
$keys = array_keys($users_emails);
$ordinal = (array_search($current,$keys)+1)%count($keys);
$next = $keys[$ordinal];
echo $next;
?>

Upvotes: 4

Pham
Pham

Reputation: 441

$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>");
}

Upvotes: 0

Hardik Thaker
Hardik Thaker

Reputation: 3078

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

Upvotes: 2

deceze
deceze

Reputation: 522085

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.

Upvotes: 43

Bajrang
Bajrang

Reputation: 8629

You can print like this :-

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

Upvotes: -1

Related Questions