Hudzilla.org - the homepage of Paul Hudson
Contents > Arrays > Array-specific functions Wish List | Report Bug | About Me ]

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.





<< 5.6.4 Converting an array to individual variables: extract()   5.6.6 Using an array as a double-ended queue: array_shift(), array_unshift(), array_push(), array_pop() >>
Table of Contents
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!



Top-right shadow
 
Bottom-left shadow Bottom shadow

Comments from other readers
Be the first to add a comment to this chapter!



Add comment
Please note that by posting a comment here you are committing it to the public domain. This is important so that others can make use of your code themselves, and also so that I can incorporate helpful notes directly into the main text. Comments are limited to 2000 characters in length.

If you are reporting an error in the content, please tell me directly.

Your name/email address:
Your comment:
 
Now, in order to verify that you're a real person, please answer this simple question: what is nine plus zero?
The answer is:
(please write in
numbers, eg 19)


Top-right shadow
 
Bottom-left shadow Bottom shadow