Finding the Position of a Value in an Array

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

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="EN" lang="EN">
<head>
<title>PHP</title>
<meta Name="Author" Content="Hann So">
</head>
<body>
<p>
<?php
$fruits = array('red'=>'Apples', 'green'=>'Grapes', 'yellow'=>'Bananas', 'orange'=>'Oranges');
print_r($fruits);
$fruit = 'Bananas';
echo "<p><b>Use array_search() to check for bananas.</b></p>";
$position = array_search($fruit, $fruits);
/* 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.
*/
if ($position !== false) {
	echo "The color of $fruit is $position.<br />";
}
else {
	echo "There're no $fruit.<br />";
}

$fruit = 'Pears';
echo "<p><b>Use array_search() to check for pears.</b></p>";
$position = array_search($fruit, $fruits);
if ($position !== false) {
	echo "The color of $fruit is $position.<br />";
}
else {
	echo "There're no $fruit.<br />";
}
?>
</p>
</body>
</html>

View the effect


Arrays | What is an array? | Creating Arrays | Iterating | Not Beginning at 0 | Initializing to a Range | Modifying | Removing Elements | Removing Duplicate | Changing Size | Key in an Array | Element in an Array | Position of a Value | Largest or Smallest Element | Reversing | Randomizing
© 2008: Hann So
email: hso@voyager.deanza.edu