Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

in_array

Checks whether a value exists in an array.

Available since: PHP 4

Syntax

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

Parameters

ParameterTypeDescription
$needlemixedThe value to look for.
$haystackarrayThe array to search in.
$strictboolIf `true`, the type is compared as well.

Return value

bool`true` if the value is found, `false` otherwise.

Examples

Looking for a value:

<?php
 
var_dump(in_array('b', ['a', 'b', 'c']));
var_dump(in_array('z', ['a', 'b', 'c']));

Output:

bool(true)
bool(false)

Without strict mode the string '1' equals the number 1:

<?php
 
var_dump(in_array('1', [1, 2, 3]));
var_dump(in_array('1', [1, 2, 3], true));

Output:

bool(true)
bool(false)

Notes

Pass true as the third argument: loose comparison produces surprising matches. The function searches values; use array_key_exists() to check for a key.

See also

  • array_search — Searches an array for a value and returns its key.
  • count — Returns the number of elements in an array.

Related recipes

In the tutorial

  • Arrays — Lists and associative arrays in PHP — creating, changing, iterating and useful functions.

Thanks for reading!

Donate to the site — we work hard for you.