Ad space (banner)
๐Ÿ˜PHP Lessons
Lesson 22 / 68

Searching an Array (in_array)

In this lesson you will learn how to search an array in PHP with in_array so you can check efficiently whether a value is present. This is for anyone searching for "PHP in_array how to use".

in_array(value, array) reports true or false depending on whether the array contains that value. It is heavily used for the simple question "is this item in the list?".

The sample code checks membership with in_array("orange", $fruits) and in_array("banana", $fruits). Compare the true result when the value is present with the false when it is not.

A common stumbling block for beginners is an unexpected match caused by type differences. Passing true as the third argument makes the comparison strict, checking the type as well. The default is a loose comparison, which can produce matches you did not intend.

The more data there is to search, the longer this takes, so for large volumes faster approaches (such as using values as associative-array keys) are worth considering. For small data sets, in_array's simplicity is a real advantage.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run PHP directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)