Ichier » coding » ichier's coding corner
{ php }  
  array_search_recursive
date 2004
update 2004
code <?php
function array_search_recursive($search,$array,$ret=array()) {        //coded by Ichier 2004
    
$res array_search($search,$array);
    if(
$res!==false) {
        
$ret[] = $res;
        return 
$ret;
    } else {
        foreach(
$array as $key=>$val) {
            if(
is_array($val)) {
                
$rett $ret;
                
$rett[] = $key;
                
$res array_search_recursive($search,$val,$rett);
                if(
$res!==false) { return $res; }
            }
        }
    }
    return 
false;
}
?>
description search for a value in an array recursively and return the keys to first match in an onedimensional array where every value is the key of the netxt depth
returns false if nothing is found
syntax <?php
array = array_search_recursive(string needle, array haystack);
?>
explanation $search is the needle, $array is the array to search in

suppose you have the array:
<?php
    $array
[0]["personal"]["name"] = "Niko";
    
$array[0]["personal"]["age"] = 25;
    
$array[0]["personal"]["town"] = "Berlin";
    
$array[0]["personal"]["family"][0]["Name"] = "Anna";
    
$array[0]["personal"]["family"][0]["age"] = 2;
    
$array[0]["personal"]["family"][0]["gender"] = "f";
    
$array[0]["personal"]["family"][1]["Name"] = "Andi";
    
$array[0]["personal"]["family"][1]["age"] = 23;
    
$array[0]["personal"]["family"][1]["gender"] = "m";
    
$array[0]["hobbies"][0] = "Music";
    
$array[0]["hobbies"][1] = "Literature";
    
$array[0]["hobbies"][2] = "Andi";
?>

and you was searchiong for "Andi":
<?php
    $array 
array_search_recursive("Andi",$array);
?>

you would get:
<?php
    $array
[0] = 0;
    
$array[1] = "personal";
    
$array[2] = "family";
    
$array[3] = 1;
    
$array[4] = "Name";
?>