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:

    $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 learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

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 ©2015 Paul Hudson. Follow me: @twostraws.