Recipe 4.12. Finding the Position of a Value in an Array


4.12.1. Problem

You want to know if a value is in an array. If the value is in the array, you want to know its key.

4.12.2. Solution

Use array_search( ) . It returns the key of the found value. If the value is not in the array, it returns false:

$position = array_search($value, $array); if ($position !== false) {     // the element in position $position has $value as its value in array $array }

4.12.3. Discussion

Use in_array( ) to find if an array contains a value; use array_search( ) to discover where that value is located. However, because array_search( ) gracefully handles searches in which the value isn't found, it's better to use array_search( ) instead of in_array( ). The speed difference is minute, and the extra information is potentially useful:

$favorite_foods = array(1 => 'artichokes', 'bread', 'cauliflower', 'deviled eggs'); $food = 'cauliflower'; $position = array_search($food, $favorite_foods); if ($position !== false) {     echo "My #$position favorite food is $food"; } else {     echo "Blech! I hate $food!"; }

Use the !== check against false because if your string is found in the array at position 0, the if evaluates to a logical false, which isn't what is meant or wanted.

If a value is in the array multiple times, array_search( ) is only guaranteed to return one of the instances, not the first instance.

4.12.4. See Also

Recipe 4.11 for checking whether an element is in an array; documentation on array_search( ) at http://www.php.net/array-search; for more sophisticated searching of arrays using regular expression, see preg_replace( ), which is found at http://www.php.net/preg-replace and Chapter 22.




PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net