Check if Array Contains Item in PHP

- 2 minutes read

You can use PHP’s built-in in_array function to check whether a given array contains a given item.

In the following example, a variable called $inArray stores a boolean that indicates whether an array of strings called $colors contains a string with a value of "green":

$colors = array('red', 'blue', 'yellow');
$inArray = in_array('green', $colors);

Because $colors does not contain "green" in the above example, $inArray will be false.

However, if $colors did contain "green", then $inArray would be true.

Link to this section Using strict checking

You can also pass a third and optional parameter to in_array, which determines whether the check should be strict.

This third parameter is false by default, but when you set it to true like in the following example, PHP will check whether the given array contains an item of the same value and type:

$numbers = array(1, 2, 3);
$inArray = in_array('3', $numbers, true);

In the above example, because the third parameter of in_array has been overwritten to true, $inArray will be false.

However, if we left that parameter alone and didn’t use strict checking, $inArray would instead be true.

This is because in_array normally just checks for items that have an equivalent value rather than also checking for matching types.

Link to this section Conclusion

The in_array function is quite simple by itself, but it’s important to check whether or not you need to use strict checking.

Sometimes you don’t have a choice, but when you do, I’d generally recommend opting for strict checking, because it is usually safer.