PHP Array Get Previous Element from Current Key

By Hardik Savani May 14, 2024 Category : PHP

Now, let's see post of php array get previous element from key. This post will give you simple example of how to get previous element of array php . This tutorial will give you simple example of php get previous key in array. you will learn php get previous key value from current key in array.

Let's see very simple example of how to get previous value from current key in php array with output:

index.php

<?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]];

}

?>

Output

Current: PHP | Previous:

Current: Laravel | Previous: PHP

Current: Angular | Previous: Laravel

Current: React | Previous: Angular

Current: Vue | Previous: React

i hope it can help you...

Tags :
Shares