PHP key => array of values ​​find prev and next entry

I have an array with key => value, and I want to get the previous and next record for this array.

Example:

$array = array(
    'one'   => 'first',
    'two'   => 'second',
    'three' => '3rd',
    'four'  => '4th'
)

When I have this key 'two', I want to receive records $array['one']and $array['three']is there any nice none foreach solution ?

+3
source share
4 answers

The two functions you are looking for are next () and prev () . Native PHP functions to do exactly what you need:

$previousPage = prev($array);
$nextPage = next($array);

, , $array ['two'] prev ($ array), $array ['one']. , , - , , next() .

+3
$array = array(
    'one'   => 'first',
    'two'   => 'second',
    'three' => '3rd',
    'four'  => '4th'
);


function getPrevNext($haystack,$needle) {
    $prev = $next = null;

    $aKeys = array_keys($haystack);
    $k = array_search($needle,$aKeys);
    if ($k !== false) {
        if ($k > 0)
            $prev = array($aKeys[$k-1] => $haystack[$aKeys[$k-1]]);
        if ($k < count($aKeys)-1)
            $next = array($aKeys[$k+1] => $haystack[$aKeys[$k+1]]);
    }
    return array($prev,$next);
}

var_dump(getPrevNext($array,'two'));

var_dump(getPrevNext($array,'one'));

var_dump(getPrevNext($array,'four'));
+1

You can try to hack something with the implementation of the CacheIterator SPL.

0
source

You can define your own class that handles operations with the base array:

Here is an example provided by adityabhai [at] gmail com [Aditya Bhatt] 09-May-2008 12:14 on php.net

<?php
class Steps {

    private $all;
    private $count;
    private $curr;

    public function __construct () {

      $this->count = 0;

    }

    public function add ($step) {

      $this->count++;
      $this->all[$this->count] = $step;

    }

    public function setCurrent ($step) {

      reset($this->all);
      for ($i=1; $i<=$this->count; $i++) {
        if ($this->all[$i]==$step) break;
        next($this->all);
      }
      $this->curr = current($this->all);

    }

    public function getCurrent () {

      return $this->curr;

    }

    public function getNext () {

      self::setCurrent($this->curr);
      return next($this->all);

    }

    public function getPrev () {

      self::setCurrent($this->curr);
      return prev($this->all);

    }

  }
?>

Demo Example:

<?php
   $steps = new Steps();
   $steps->add('1');
   $steps->add('2');
   $steps->add('3');
   $steps->add('4');
   $steps->add('5');
   $steps->add('6');
   $steps->setCurrent('4');
   echo $steps->getCurrent()."<br />";
   echo $steps->getNext()."<br />";
   echo $steps->getPrev()."<br />";
   $steps->setCurrent('2');
   echo $steps->getCurrent()."<br />";
   echo $steps->getNext()."<br />";
   echo $steps->getPrev()."<br />";
?>
0
source

All Articles