Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have an array with specific keys:

array(
    420 => array(...), 
    430 => array(...), 
    555 => array(...)
)

In my application I know current key (for example 555). And I want to get the previous array element. In this example it is array element with key 430. How can I do this in PHP? I tried to work with prev(), but for this function we should know current array element. I didn't find function, what set the current array element. Help me.

Thank you in advance. Sorry for my english.

share|improve this question
you can simple iterate over it. – Your Common Sense Jan 25 '11 at 11:04
1  
Are the keys in sorted order? – Gumbo Jan 25 '11 at 11:04
As you can see from the explanation below, there is not a single reason to set any pointers in your case. They have another, very limited use. – Your Common Sense Jan 25 '11 at 11:28
@Gumbo. No, keys isn't sorted. – plutov Jan 25 '11 at 11:33

7 Answers

up vote 10 down vote accepted

One option:

To set the internal pointer to a certain position, you have to forward it (using key and next, maybe do a reset before to make sure you start from the beginning of the array):

while(key($array) !== $key) next($array);

Then you can use prev():

$prev_val = prev($array);
// and to get the key
$prev_key = key($array);

Depending on what you are going to do with the array afterwards, you might want to reset the internal pointer.

If the key does not exist in the array, you have an infinite loop, but this could be solved with:

 while(key($array) !== null && key($array) !== $key)

of course prev would not give you the right value anymore but I assume the key you are searching for will be in the array anyway.

share|improve this answer
Cool non-foreach solution that actually works with the internal array pointer, +1 – BoltClock Jan 25 '11 at 11:12
@Bolt whats so cool??? – Your Common Sense Jan 25 '11 at 11:13
1  
the fact that we would usually go over the array with foreach but he had a different approach that works well and it also uses internal pointers. +1 – RobertPitt Jan 25 '11 at 11:14
1  
So, you just perfectly explained, why these pointers just shouldn't be used. as for key($array) - imagine we have a regular enumerated array... ;) – Your Common Sense Jan 25 '11 at 11:29
@Col. Shrapnel: Better? :) – Felix Kling Jan 25 '11 at 11:30
show 8 more comments

Solution with fast lookups: (if you have to do this more than once)

$keys = array_flip(array_keys($array));
$values = array_values($array);
return $values[$keys[555]-1];

array_flip(array_keys($array)); will return an array mapping keys to their position in the original array, e.g. array(420 => 0, 430 => 1, 555 => 2).

And array_values() returns an array mapping positions to values, e.g. array(0 => /* value of $array[420] */, ...).

So $values[$keys[555]-1] effectively returns the previous elements, given that the current one has key 555.

Alternative solution:

$keys = array_keys($array);
return $array[$keys[array_search(555, $keys)-1]];
share|improve this answer

You can iterate through the array in reverse and return the next iteration after finding the search value.

$found = false;
foreach(array_reverse($array, true) as $key=>$value) {
  if ($found) {
    print "$key => $value\n";
    break;
  } else if ($key == 555) {
    $found = true;
  }
}

http://ideone.com/2WqmC

share|improve this answer

I solved this issue in this way:

function getPrevKey($key, $hash = array())
{
    $keys = array_keys($hash);
    $found_index = array_search($key, $keys);
    if ($found_index === false || $found_index === 0)
        return false;
    return $keys[$found_index-1];
}

@return previous key or false if no previous key is available

Example:

$myhash = array(
    'foo' => 'foovalue',
    'goo' => 'goovalue',
    'moo' => 'moovalue',
    'zoo' => 'zoovalue'
);

echo "TEST: ". getPrevKey('zoo', $myhash); // prints moo
share|improve this answer

Just iterate over the array

$_index = null;
foreach($myarray as $index => $value)
{
    if($key == $my_index) // if($key == 550)
    {
        break;
    }
    $_index = $index;
}

echo $_index; //the prev key from 550;

An alternative solution is to get the keys of your array within an enumerated array like so:

$keys = array_keys($my_array);

as the keys array is index you can move the the previous key like so:

$required_key = (array_search(550,$keys,true) - 1);

this will fine the value of 550, and return its index within the keys, remove one to get the previous index

key we have our previous key to get the value from the original array

$value = $my_array[$required_key];
share|improve this answer
+1 for the array_keys approach. Compact, transparent and easily tweakable. – mmdanziger Jun 7 '12 at 11:48

This is a simple solution for taking previous and next items, even if we are at the ends of the array.

<?php
    $current_key; // the key of the item we want to search from

    if (isset($array[$current_key+1])) 
    {

        $array_next = $array[$current_key+1]; // get the next item if there is 
    } 
    else 
    {       
        $array_next = $array[0]; // if not take the first (this means this is the end of the array)             
    }       

    if (isset($array[$current_key-1])) 
    {

        $array_prev = $array[$current_key-1]; // get the previous item if there is 
    } 
    else 
    {   
        $array_prev = $array[count($array)-1]; // if not take the last item (this means this is the beginning of the array)             
    }

?>
share|improve this answer

@Luca Borrione's solution was helpful. If you want to find both previous and next keys, you may use the following function:

function getAdjascentKey( $key, $hash = array(), $increment ) {
    $keys = array_keys( $hash );    
    $found_index = array_search( $key, $keys );
    if ( $found_index === false ) {
        return false;
    }
    return $keys[$found_index+$increment];
}

Usage:

// previous key / returns false if result found at first key
getAdjascentKey( $key, $hash, -1 );

// next key / returns false if result found at last key
getAdjascentKey( $key, $hash, +1 );
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.