I'm amazed many answers, including voted answers, point to an embedded code as a solution, filtering the array to a single occurrence, manually encoded in a conditional-only.
Well ... My suggestion is similar to that given by the @Cahe friend, but it's much leaner and kills the problem with sniper precision, and, by the way, still uses the more modern features of the language: Iterators. p>
It was not a solution I created, hence the documentation in English, but I kept the author's credits, including the link from where the snippet was removed. But unfortunately, or the same has been removed from the manual, or deleted during the site's repagination.
/**
* Searches value inside a multidimensional array, returning its index
*
* Original function by "giulio provasi" (link below)
*
* @param mixed|array $haystack
* The haystack to search
*
* @param mixed $needle
* The needle we are looking for
*
* @param mixed|optional $index
* Allow to define a specific index where the data will be searched
*
* @return integer|string
* If given needle can be found in given haystack, its index will
* be returned. Otherwise, -1 will
*
* @see http://www.php.net/manual/en/function.array-search.php#97645
*/
function search( $haystack, $needle, $index = NULL ) {
if( is_null( $haystack ) ) {
return -1;
}
$arrayIterator = new \RecursiveArrayIterator( $haystack );
$iterator = new \RecursiveIteratorIterator( $arrayIterator );
while( $iterator -> valid() ) {
if( ( ( isset( $index ) and ( $iterator -> key() == $index ) ) or
( ! isset( $index ) ) ) and ( $iterator -> current() == $needle ) ) {
return $arrayIterator -> key();
}
$iterator -> next();
}
return -1;
}
To use, of course, it is enough to invoke the function by passing the array to be fetched in the first argument and what is searched in the second.
var_dump( search( $valores, '5745,5744,7' ) ); // Saída int(2)
Optionally we have the third argument that allows you to restrict the search to a specific index of the array.
In the example use immediately above would be:
var_dump( search( $valores, '5745,5744,7', 'fk' ) );
It is not a performance gain because all logic resides in a single IF, but it is an alternative that deserves to be taken into account.
The function returns an integer that should be used to access the array's indexes:
var_dump( $valores[ search( $valores, '5745,5744,7', 'fk' ) ] );
Just notice that this didactic example takes into account a real and existing value. In a real application where the value you are looking for may not exist, a check should be made if the function returns -1 , since -1 is obviously not a valid index for an array, even if it is unduly valid for PHP.