Description

Parameters

needle

The searched value.

Note:

If needle is a string, the comparison is done
in a case-sensitive manner.

haystack

The array.

strict

If the third parameter strict is set to TRUE
then the array_search() function will search for
identical elements in the
haystack. This means it will also check the
types of the
needle in the haystack,
and objects must be the same instance.

Return Values

Returns the key for needle if it is found in the
array, FALSE otherwise.

If needle is found in haystack
more than once, the first matching key is returned. To return the keys for
all matching values, use array_keys() with the optional
search_value parameter instead.

Warning

This function may
return Boolean FALSE, but may also return a non-Boolean value which
evaluates to FALSE. Please read the section on Booleans for more
information. Use the ===
operator for testing the return value of this
function.

Changelog

Version

Description

5.3.0

As with all internal PHP functions as of 5.3.0,
array_search() returns NULL if invalid parameters
are passed to it.

If you are using the result of array_search in a condition statement, make sure you use the === operator instead of == to test whether or not it found a match. Otherwise, searching through an array with numeric indicies will result in index 0 always getting evaluated as false/null. This nuance cost me a lot of time and sanity, so I hope this helps someone. In case you don't know what I'm talking about, here's an example:

If you only know a part of a value in an array and want to know the complete value, you can use the following function:<?phpfunction array_find($needle, $haystack){ foreach ($haystack as $item) { if (strpos($item, $needle) !== FALSE) { return $item; break; } }}?>The function returns the complete first value of $haystack that contains $needle.

I had an array of arrays and needed to find the key of an element by comparing actual reference.Beware that even with strict equality (===) php will equate arrays via their elements recursively, not by a simple internal pointer check as with class objects. The === can be slow for massive arrays and also crash if they contain circular references.

This function performs reference sniffing in order to return the key for an element that is exactly a reference of needle.

/** * @return integer * @param var $needle * @param array $haystack * @desc Feed a sorted array to $haystack and a value to search for to $needle. It will return false if not found or the index where it was found. This function is superfast. Try an array with 50.000 elements and search for something, you will be amazed.*/function binsearch($needle, $haystack){$high = count($haystack);$low = 0;

Sometimes you need to find a given value in a sorted array or - if not found - detect the place where it should be. After that you can for example split the array into two halves, the greater and the smaller one.

greenmr, dennis.decoene and php at celerondude had all posted very good binary search functions but these functions all return false if the needle was not found in the haystack. I've tweaked greenmr's code a little:

Now, the function returns true if it finds something and false otherwise. If a needle was found, then $probe will contain it's position. Otherwise, $probe will contain position of where the needle would be if it were there :). This is possible because we pass $probe by reference.

I needed a way to find the parent hierarchy of a multidimensional array. Being the rogue that I am, I got to coding before searching the manual and came up with two little functions that will return a parent stack for a first find and a complete parent stack, similar in nature to the solution presented by jette at nerdgirl dot dk without all the extra stuff or use of eval(). ;)

<?php/** * Gets the parent stack of a string array element if it is found within the * parent array * * This will not search objects within an array, though I suspect you could * tweak it easily enough to do that * * @param string $child The string array element to search for * @param array $stack The stack to search within for the child * @return array An array containing the parent stack for the child if found, * false otherwise */function getParentStack($child, $stack) { foreach ($stack as $k => $v) { if (is_array($v)) {// If the current element of the array is an array, recurse it and capture the return$return = getParentStack($child, $v);

// If the return is an array, stack it and return itif (is_array($return)) { return array($k => $return); } } else {// Since we are not on an array, compare directlyif ($v == $child) {// And if we match, stack it and return itreturn array($k => $child); } } }

// Return false since there was nothing foundreturn false;}

/** * Gets the complete parent stack of a string array element if it is found * within the parent array * * This will not search objects within an array, though I suspect you could * tweak it easily enough to do that * * @param string $child The string array element to search for * @param array $stack The stack to search within for the child * @return array An array containing the parent stack for the child if found, * false otherwise */function getParentStackComplete($child, $stack) {$return = array(); foreach ($stack as $k => $v) { if (is_array($v)) {// If the current element of the array is an array, recurse it // and capture the return stack$stack = getParentStackComplete($child, $v);

// If the return stack is an array, add it to the returnif (is_array($stack) && !empty($stack)) {$return[$k] = $stack; } } else {// Since we are not on an array, compare directlyif ($v == $child) {// And if we match, stack it and return it$return[$k] = $child; } } }

one thing to be very aware of is that array_search() will fail if the needle is a string and the array itself contains values that are mixture of numbers and strings. (or even a string that looks like a number)

The problem is that unless you specify "strict" the match is done using == and in that case any string will match a numeric value of zero which is not what you want.

-----

also, php can lookup an index pretty darn fast. for many scenarios, it is practical to maintain multiple arrays, one in which the index of the array is the search key and the normal array that contains the data.

I was trying to use array_search to retrieve all the values that match a given needle, but it turns out only the first match key is returned. I built this little function, which works just like array_search, but returns all the keys that match a given needle instead. The output is an array.

<?php

$haystack = array('a','b','a','b');

$needle = 'a';

print_r(array_search_all($needle, $haystack));

//Output will be// Array// (// [0]=>1// [1]=>3// )

function array_search_all($needle, $haystack){#array_search_match($needle, $haystack) returns all the keys of the values that match $needle in $haystack

When searching for a string and the array contains 0 (zero), the string is casted to (int) by the type-casting which is always 0 (perhaps the opposite is the proper behaviour, the array value 0 should have been casted to string). That produces unexpected results if strict comparison is not used:

Combining syntax of array_search() and functionality of array_keys() to get all key=>value associations of an array with the given search-value:<?phpfunction array_search_values( $m_needle, $a_haystack, $b_strict = false){ return array_intersect_key( $a_haystack, array_flip( array_keys( $a_haystack, $m_needle, $b_strict)));}?>

// Check $result. if (is_array($multiArray)) {// An array was found at the end of the search. Return true.$result = true; } else if ($result == '') {// There was nothing found at the end of the search. Return false.$result = false; }

Be absolutely sure to check that your code that uses array_search now checks for 'false' too if you upgrade to PHP 4.2.0!

I was using array_search in my page authentication routines and this change had the fun side-effect of causing my code to always think a user had full permissions! It was letting anyone click through to our installation of phpMyAdmin. Not good indeed!

In this code I write a code to find next and previous element of an array using current element of that array. Let suppose if we are in element 9 and have to access its next and previous element then this code be helpful for someone.

If you encounter a situation where condition test is failing on the result of either array_search or in_array, even when using "===" and "!==", make sure to set $strict = true in your array_search() or in_array() function call.

This is necessary in any instance where you have an array value equal to the integer zero. As soon as you put the zero in quotes or double quotes (a string), the evaluation works with in_array & array_search without the $strict parameter being set.