PHP 8 reference · Array Functions
PHP in_array() Function
Check whether a value exists in an array. Pass true as the third argument for a strict (===) comparison.
PHP 8 Since 4.0
Syntax
in_array(mixed $needle, array $haystack, bool $strict = false): bool
Parameters
| Parameter | Description |
|---|---|
needle |
The value to find. |
haystack |
The array to search. |
strict optional |
true also checks the type (===). Default: false |
Return value
true if found.
Examples
<?php
$roles = ["admin", "editor"];
var_dump(in_array("editor", $roles));
var_dump(in_array("guest", $roles));
Output
bool(true) bool(false)
<?php
var_dump(in_array("1e1", ["10"])); // loose: both are 10
var_dump(in_array("1e1", ["10"], true)); // strict
Output
bool(true) bool(false)
Common mistakes
- Loose comparison can match unexpected values; pass
trueas the third argument unless you need conversion. - For many lookups in a big list, flip it once (
$set = array_flip($list)) and useisset($set[$value]).
Version history
| Version | Change |
|---|---|
| PHP 4.0 | Added |
In other languages
array.includes()· JavaScript
Related
array_search()· Search an array for a value and return the first matching key, or false if it isn't there.array_key_exists()· Check whether an array has a given key, even if its value is null. isset() returns false for null values.array_any()· Return true if at least one element passes a callback test, stopping at the first match. Added in PHP 8.4.- PHP Arrays · tutorial
- PHP Array Functions · tutorial