in_array

Checks if a value exists in an array

Syntax

in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] ) : bool

Parameters

needle

The searched value.

Note: If needle is a string, the comparison is done in a case-sensitive manner.

haystack

The array.

strict

If the third parameter strict is set to TRUE then the in_array() function will also check the types of the needle in the haystack.

Return

Returns TRUE if needle is found in the array, FALSE otherwise.

Examples

needle haystack

<?

$needle = 2;
$haystack = array("1", "2", "3", "4");

$return = in_array($needle, $haystack);

var_export($return);

?>
true

strict

<?

$needle = 2;
$haystack = array("1", "2", "3", "4");
$strict = true;

$return = in_array($needle, $haystack, $strict);

var_export($return);

?>
false

1

<?

$haystack = array("Irix", "Linux", "Mac", "NT");

$needle = "Linux";
if (in_array($needle, $haystack)) {
    echo "$needle\n";
}

$needle = "mac";
if (in_array($needle, $haystack)) {
    echo "$needle\n";
}

?>
Linux

2

<?

$haystack = array("1.2", 3.4, 5.6);
$strict = true;

$needle = "3.4";
if (in_array($needle, $haystack, $strict)) {
    echo "$needle\n";
}

$needle = 5.6;
if (in_array($needle, $haystack, $strict)) {
    echo "$needle\n";
}

?>
5.6

3

<?

$haystack = array(array("p", "h", "p"), array("o", "s", "b"), "o");

$needle = array("p", "h", "p");
if (in_array($needle, $haystack)) {
    echo "php\n";
}

$needle = array("n", "e", "e", "d", "l", "e");
if (in_array($needle, $haystack)) {
    echo "needle\n";
}

$needle = "o";
if (in_array($needle, $haystack)) {
    echo "o\n";
}

?>
php
o

4

<?

$haystack = array(
    "one" => null,
    "two" => false,
    "three" => true,
    "four" => 10,
    "five" => "20"
);
$strict = true;

echo "loose:\n";
echo in_array(null, $haystack);
echo in_array(false, $haystack);
echo in_array(true, $haystack);
echo in_array(10, $haystack);
echo in_array("20", $haystack);
echo " ";
echo in_array("zero", $haystack);
echo in_array("one", $haystack);
echo in_array("10", $haystack);
echo in_array(20, $haystack);
echo in_array(array(), $haystack);

echo "\n\nstrict:\n";
echo in_array(null, $haystack, $strict);
echo in_array(false, $haystack, $strict);
echo in_array(true, $haystack, $strict);
echo in_array(10, $haystack, $strict);
echo in_array("20", $haystack, $strict);
echo " ";
echo in_array("zero", $haystack, $strict);
echo in_array("one", $haystack, $strict);
echo in_array("10", $haystack, $strict);
echo in_array(20, $haystack, $strict);
echo in_array(array(), $haystack, $strict);

?>
loose:
11111 11111

strict:
11111 

PHP

Home Menu