简体   繁体   中英

Getting the next value in a php array

I want to get the next value in a PHP array for example:

$array = array('a', 'b', 'c', 'd', 'e', 'f');
$current_array_val = 'c';
//so I want to run a code to get the next value in the array and
$next_array_val = 'd';
//And also another code to get the previous value which will be
$prev_array_val = 'b';

Please how do I run my code to achieve this

http://php.net/manual/ro/function.array-search.php

$index = array_search($current_array_val, $array);
if($index !== false && $index > 0 ) $prev = $array[$index-1];
if($index !== false && $index < count($array)-1) $next = $array[$index+1];

use next() function:

In addition: use current() or prev()

$array = array('a', 'b', 'c', 'd', 'e', 'f');

$current= current($array); // 'a'
$nextVal = next($array); // 'b'
$nextVal = next($array); // 'c'

// ... 

Here are another solution,

$values = array_values($array);
$search=array_search($current_array_val,$values);
$next=$values[(1+$search)%count($values)];
$array = array('a', 'b', 'c', 'd', 'e', 'f');

$flipped_array = array_flip($array);

$middle_letter = 'c'; //Select your middle letter here

$index_of_middle_letter = $flipped_array[$middle_letter];

$next_index = $index_of_middle_letter + 1;
$prev_index = $index_of_middle_letter - 1;
$next_item = $array[$next_index];
$prev_item = $array[$prev_index];

array_search() is slower than doing an array_flip() when it comes to dealing with large arrays. The method I have described above is far more scalable.

Use array_search, and increment/decrement for next/prev item in array.

$array = array('a', 'b', 'c', 'd', 'e', 'f');
$current_array_val = array_search('c', $array);
//so I want to run a code to get the next value in the array and
$next_array_val = $array[$current_array_val+1];
//And also another code to get the previous value which will be
$prev_array_val = $array[$current_array_val-1];


echo $next_array_val; // print d
echo $prev_array_val; // print b

Take a look at this code sample for a better understanding of the object-oriented way of navigating through arrays:

$array = array('a', 'b', 'c', 'd', 'e', 'f');

$pointer = 'c';

// Create new iterator
$arrayobject = new ArrayObject($array);
$iterator = $arrayobject->getIterator();

$iterator->seek($pointer);     //set position

// Go to the next value
$iterator->next();             // move iterator 

// Assign next value to a variable
$nextValue = $iterator->current();

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