note 107840 deleted from function.array-search by salathe

From: Date: Thu, 08 Mar 2012 22:41:05 +0000
Subject: note 107840 deleted from function.array-search by salathe
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-186551@lists.php.net to get a copy of this message
Note Submitter: kriscraig at php dot net ---- My answer to recursive searching. In this instance, we're only searching for a single value (not an array of values), but the haystack array is of variable depth. This function will, therefore, return an array of keys, essentially showing the "path" to the value we're searching for. <?php function array_search_recursive( $needle, $haystack, $keys = array() ) { $key = array_search( $needle, $haystack ); if ( $key !== FALSE ) { $keys[] = $key; return $keys; } else { foreach ( $haystack as $key => $value ) { if ( is_array( $value ) ) { $res = array_search_recursive( $needle, $value, $keys ); if ( $res !== FALSE ) { if ( count( $res ) == 1 ) { $keys[] = $res[0]; } $keys[] = $key; return $keys; } } } return FALSE; } } /* Now, here's a simple example. --Kris */ $arr = array( 0 => "blah", 1 => array(), "WHAT?!" => array( "bleh" => 42, 37 => "OK" ), 3 => "NOPE" ); var_dump( array_reverse( array_search_recursive( "OK", $arr ) ) ); ?> The above will output: array(2) { [0]=> string(6) "WHAT?!" [1]=> int(37) }

« previous php.notes (#186551) next »