Morten Hagh
Morten Hagh

Reputation: 2113

get next value in php array

I have an array where I want to get the next value.

$sorting = array(0 => "H 101", 1 => "S 101", 2 => "R 172", 3 => "D 141", 4 => "T 101", 5 => "K 101", 6 => "A 182", 7 => "G 101");

I have the current value taken from a SELECT statement. I have tried array_search but I can't get it to do want I want.

Let's say my current value is S 101, how can I get it to give me "R 172" as the next value which I then can use in a new SELECT statement.

And I also want it to get back to the first value (H 101) if the current value is the last (G 101).

Upvotes: 0

Views: 9045

Answers (4)

Laxman Rana
Laxman Rana

Reputation: 2924

next() and prev() deal with the internal pointer of the array while your script is processing.

$current_index = array_search($current_id, $array);

// Find the index of the next/prev items
$next = $current_index + 1;
$prev = $current_index - 1;

Your HTML:

<?php if ($prev > 0): ?>
    <a href="<?= $array[$prev] ?>">Previous</a>
<?php endif; ?>

<?php if ($next < count($array)): ?>
    <a href="<?= $array[$next] ?>">Next</a>
<?php endif; ?>

Upvotes: 6

DonCallisto
DonCallisto

Reputation: 29912

Operationally you could retrive the index of your current value in that way

$key = array_search($currValue, $sorting);

Then you should do myNewValue = $sorting[($key+1)%8] or if you don't know the size of array, you have to do myNewValue = $sorting[($key+1)%(count($sorting)+1)]

Upvotes: 1

Waynn Lue
Waynn Lue

Reputation: 11375

Assuming you know you're not going to go off the end of your array and that your input exists:

$sorting = array(0 => "H 101", 1 => "S 101", 2 => "R 172", 3 => "D 141", 4 => "T 101", 5 => "K 101", 6 => "A 182", 7 => "G 101");

$key = array_search("H 101", $sorting);
$returnValue = $sorting[$key + 1];

Upvotes: 0

deed02392
deed02392

Reputation: 5022

Why have you explicitly specified the indices? These would be the same had you not done it.

From what I understand, array_search would be suitable for what you want.

$current = 'S 101';
$nextkey = array_search($current, $sorting) + 1;
if($nextkey == count($sorting)) {
    // reached end of array, reset
    $nextkey = 0;
}

$next = $sorting[$nextkey];

HOWEVER, if I understand you correctly you're looping through this array and making queries on it. How about posting what you want in terms of query result, as there may be a better solution (i.e. MySQL IN())

Upvotes: 4

Related Questions