PHP in_array function
The PHP function in_array is responsible for checking if a given value exists in any of the elements of an array.
Description / Descripciónin_array(mixed $needle, array $haystack, bool $strict = false): bool
Its possible syntaxes are as follows.
Sintaxis / Sintaxin_array($needle,$haystack)
in_array($needle,$haystack,true)
Parameters
$needle
– the value to be searched for within the array, in fact, “needle” means needle and “haystack” would be the haystack, alluding to the saying “looking for a needle in a haystack.”
"name"
≠ "Name"
$haystack
– is the array where we will search for our value.
$strict
– this value is false by default. You should only add this parameter as true if you want the function to also check that the types of $needle
and $haystack
are the same.
Note:
Prior to PHP 8.0.0, a
php.netstring
needle
will match an array value of0
in non-strict mode, and vice versa. That may lead to undesirable results. Similar edge cases exist for other types, as well. If not absolutely certain of the types of values involved, always use thestrict
flag to avoid unexpected behavior.
Returns
true if $needle is found in the array ($haystack),
false if $needle is not found.
Use
This function is generally used when you have a set of values retrieved from a database, and you want to check if they correlate or even in conjunction with “explode” when you obtain a URL or a path. The “explode” function can be used in combination with “in_array.”
Let’s look at a slightly more elaborate example than the simple one we could create.
$persona = [ "nombre" => "Jorge", "edad" => 40, "ciudad" => "Mexico", ]; if (in_array("40", $persona)) { echo "El valor 40 existe en el array persona."; } else { echo "El valor 40 no existe en el array persona."; }
Notice that here we are using an associative array, so you can see that in these cases, you can also use this function.