HomeMenu
Jesus · Bible · HTML · CSS · JS · PHP · SVG · Applications

in_array

Description

The in_array of Array for PHP checks if a value exists in an array.

Syntax

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

Parameters

needle

The search value.

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

haystack

The array.

strict

The type of the needle in the haystack is also checked.

Return

Returns true if needle is found in the array, false otherwise.

Examples

1 · needle haystack

<?

$needle = 2;
$haystack =
[
    "1",
    "2",
    "3"
];

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

var_export($return);
true

2 · strict

<?

$needle = 2;
$haystack =
[
    "1",
    "2",
    "3"
];
$strict = true;

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

var_export($return);
false

3 · case-sensitive

<?

$needle = "MacOS";
$haystack =
[
    "audioOS",
    "iOS",
    "iPadOS",
    "macOS",
    "tvOS",
    "visionOS",
    "watchOS"
];

if(in_array($needle, $haystack))
{
    echo "found";
}
else
{
    echo "not found";
}
not found

4 · array

<?

$needle =
[
    "f",
    "o",
    "u",
    "n",
    "d"
];
$haystack =
[
    "n",
    "o",
    "t",
    [
        "n",
        "o",
        "t"
    ],
    [
        "f",
        "o",
        "u",
        "n",
        "d"
    ]
];

if(in_array($needle, $haystack))
{
    print_r($needle);
}
Array
(
    [0] => f
    [1] => o
    [2] => u
    [3] => n
    [4] => d
)

5 · loose

<?

$haystack =
[
    "one" => null,
    "two" => false,
    "three" => true,
    "four" => 10,
    "five" => "20"
];
$strict = true;

echo "loose:" . PHP_EOL
. in_array(null, $haystack)
. in_array(false, $haystack)
. in_array(true, $haystack)
. in_array(10, $haystack)
. in_array("20", $haystack)
. " "
. in_array("zero", $haystack)
. in_array("one", $haystack)
. in_array("10", $haystack)
. in_array(20, $haystack)
. in_array(array(), $haystack)
. PHP_EOL . PHP_EOL
. "strict:" . PHP_EOL
. in_array(null, $haystack, $strict)
. in_array(false, $haystack, $strict)
. in_array(true, $haystack, $strict)
. in_array(10, $haystack, $strict)
. in_array("20", $haystack, $strict)
. " "
. in_array("zero", $haystack, $strict)
. in_array("one", $haystack, $strict)
. in_array("10", $haystack, $strict)
. in_array(20, $haystack, $strict)
. in_array(array(), $haystack, $strict);
loose:
11111 11111

strict:
11111