note 107840 added to function.array-search

From: Date: Thu, 08 Mar 2012 22:25:51 +0000
Subject: note 107840 added to function.array-search
Groups: php.notes 
Request: Send a blank email to php-notes+get-186550@lists.php.net to get a copy of this message
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) } ---- Server IP: 192.41.42.26 Probable Submitter: 173.10.123.113 ---- Manual Page -- http://www.php.net/manual/en/function.array-search.php Edit -- https://master.php.net/note/edit/107840 Del: integrated -- https://master.php.net/note/delete/107840/integrated Del: useless -- https://master.php.net/note/delete/107840/useless Del: bad code -- https://master.php.net/note/delete/107840/bad+code Del: spam -- https://master.php.net/note/delete/107840/spam Del: non-english -- https://master.php.net/note/delete/107840/non-english Del: in docs -- https://master.php.net/note/delete/107840/in+docs Del: other reasons-- https://master.php.net/note/delete/107840 Reject -- https://master.php.net/note/reject/107840 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#186550) next »