5.6.5 Checking whether an element exists: in_array()This is NOT the latest copy of this book; click here for the latest version.
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.
|
Want to see this stuff in print? PHP in a Nutshell takes the core topics covered here, adds in thousands of edits from the editorial team and myself, and combines them to make an unbeatable reference for PHP programmers at all levels.
My latest book has hundreds more tips on how to use PHP, Apache, and MySQL, plus Perl, Python, shell scripts, performance tuning, and more!
|