Join WhatsApp ChannelJoin Now

Get Previous Array Element from Current Key in Php

Hi Dev,

Today, i we will show you get previous array element from current key in php. This article will give you simple example of get previous array element from current key in php. you will learn get previous array element from current key in php.

So let’s follow few step to create example of get previous array element from current key in php.

Example:

<?php
  
$myArray = ["PHP", "Laravel", "Angular", "React", "Vue"];
   
foreach($myArray as $key => $value){
	echo "<br/> Current: ". $value;
	echo " | Previous: ". getPrevValue($key, $myArray);
}
  
function getPrevValue($key, $hash = array())
{
    $keys = array_keys($hash);
    $found_index = array_search($key, $keys);
    if ($found_index === false || $found_index === 0)
        return false;
    return $hash[$keys[$found_index-1]];
}
 
?>
  Current: PHP | Previous:
  Current: Laravel | Previous: PHP
  Current: Angular | Previous: Laravel
  Current: React | Previous: Angular
  Current: Vue | Previous: React

Recommended Posts