I have this array:
$test = array( "a" => "b",
"c" => array("foo" => "bar",
"3" => "4",
),
"e" => "f",);
I want to create a function that finds the previous value in this array, given a certain value, for example find("bar", $test);
should return "b".
This is what I got:
function find($needle, $array, $parent = NULL)
{
//moves the pointer until it reaches the desired value
while (current($array) != $needle){
//if current value is an array, apply this function recursively
if (is_array(current($array))){
$subarray = current($array);
//passes the previous parent array
find($needle, $subarray, prev($array));
}
//once it reaches the end of the array, end the execution
if(next($array) == FALSE){
return;
}
}
//once the pointer points to $needle, run find_prev()
find_prev(prev($array), $parent);
}
function find_prev($prev, $parent = NULL)
{
// in case there is no previous value in array and there is a superior level
if (!$prev && $parent) {
find_prev($parent);
return;
}
// in case previous value is an array
// find last value of that array
if (is_array($prev) && $prev){
find_prev(end($prev), $parent));
return;
} else {
$GLOBALS['pre'] = $prev;
}
}
For pedagogical reasons and since I have devoted some time to this function, it would be great if you could provide any hints about why this isn't working rather than any other simpler solution that you might have.