Checking if an Element is in an Array

You want to know if an array contains a certain value.

Use in_array() to check if an element of an array holds a value.

<!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 in_array() to check for bananas.</b></p>";
if (in_array($fruit, $fruits)) {
	echo "It's in the array.<br />";
}
else {
	echo "It's not in the array.<br />";
}

$fruit = 'Pears';
echo "<p><b>Use in_array() to check for pears.</b></p>";

if (in_array($fruit, $fruits)) {
	echo "It's in the array.<br />";
}
else {
	echo "It's not in the array.<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