I’m trying to create a function that will loop through an array of various lengths. During the loop, a function is run to see if the immediately prior item (the item at current key minus 1) matches what is in the array.
Here are two examples of arrays:
$terms1 = array(
0 => 'MEL',
1 => 'Appliances',
2 => 'Clothes Dryers',
3 => 'Clothes dryers - electric'
);
$terms2 = array(
0 => 'Clothes Dryers',
1 => 'Clothes dryers - electric'
);
And here is the function to be run within the loop… this function will return a value and then I will compare that to what is in the array in the immediately prior location (current key minus 1). This pulls from a db.
getParent($terms1[3]); //Would output the value I want to compare to $terms1[2]
I’ve tried something like this:
$fail = null;
foreach(array_reverse($terms1, true) as $key => $value){
if($key > 0){
$priorkey = $key - 1;
if(getParent($terms1[$key]) != $terms1[$priorkey]){
$fail = true;
}
}
}
return $fail;
I think I need a recursive function… any help or nudges in the right direction would be appreciated.
1 Answer