Imagine some arrays set up in a PHP script something like this:
$foo = array(
'bob'=>976,
'Jack'=>'Octopus',
'bar'=>'baz',
'pi'=>'irrational',
'other'=>123
);
$biz = array(
'Harry'=>'Dogs',
'Zim'=>'zoom',
'bar'=>'baz',
);
Now lets say (for reasons) I want to get the content of the array one index before "bar". Like this:
function get_before($ar,$what){
// ... the bit I'm still working on
}
echo get_before($foo,'bar'); // should be Octopus
echo get_before($biz,'bar'); // should be zoom
I figure that what I want is the key that comes before mine. Is there a way to get that? (You can assume that the arrays will rarely be as big as 50 elements).
I've been toying with using array_keys
, doing a search on the new array, getting the index value of the result minus one to find the new key, then using that key to get my target. It just seems needless intensive and hackish - a simpler approach would make me happier as the function I create will get called a lot every page load.