Checking whether an element exists
bool in_array ( mixed needle, array haystack [, bool strict])
The in_array() function does precisely what you might think - if you pass it a value and an array it will return true if the value is in the array, otherwise false. This following example show it in action:
<?php
$needle = "Sam";
$haystack = array("Johnny", "Timmy", "Bobby", "Sam", "Tammy", "Danny", "Joe");
if (in_array($needle, $haystack)) {
print "$needle is in the array!\n";
} else {
print "$needle is not in the array\n";
}
?>
In_array() has an optional boolean third parameter (set to false by default) that defines whether you want to use strict checking or not. If parameter three is set to true, PHP will only return true if the value is in the array and it is of the same type - that is, if they are identical in the same way as the === operator (three equals signs). This is not used very often, but it is important that you are at least aware of its existence.
Next chapter: Using an array as a double-ended queue >>
Previous chapter: Converting an array to individual variables
Jump to:
Home: Table of Contents



Copyright 2012 Future Publishing Limited (company
registered number 2008885), a company registered
in England and Wales whose registered office is at
Beauford Court, 30 Monmouth Street, Bath, BA1 2BW, UK