PHP in_array() Function

Quick summary: The PHP in_array() function checks if a value exists in an array.

PHP in_array() Syntax

in_array(mixed $needle, array $haystack, bool $strict = false): bool
PHP

PHP in_array() Basic examples

var_dump(in_array('apple', ['apple','banana']));
PHP
Output:
bool(true)

Returns true if the value exists.

var_dump(in_array('orange', ['apple','banana']));
PHP
Output:
bool(false)

Returns false if the value does not exist.

PHP in_array() Real-world usage

$allowed = ['jpg','png'];
if (in_array('jpg', $allowed)) {
    echo 'Allowed';
}
PHP
Output:
Allowed

Validates allowed file extensions.

PHP in_array() Edge cases

var_dump(in_array(0, ['0', false]));
PHP
Output:
bool(true)

Loose comparison is used by default.

PHP in_array() Common mistakes

Forgetting strict mode

Loose comparison may cause unexpected matches.

Incorrect
in_array(0, ['0', false]);
Correct
in_array(0, ['0', false], true);

Pass true as the third argument for strict comparison.

PHP in_array() Frequently Asked Questions

What does in_array() do?

in_array() checks if a value exists in an array.

What does it return?

Boolean.

Is it case-sensitive?

Yes.

Supports strict mode?

Yes.

Difference from array_search()?

Returns boolean instead of key.

Works with associative arrays?

Yes.

Use case?

Checking existence of value.

Performance?

Linear.

Does it modify array?

No.

Handles duplicates?

Yes.

Can return false negatives?

Without strict mode.

Supports objects?

Yes.

PHP in_array() Related PHP Functions