Blog de programación, errores, soluciones

Chose Language:
comments
Author: Admin/Publisher |finished | checked

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ón
in_array(mixed $needle, array $haystack, bool $strict = false): bool

Its possible syntaxes are as follows.

Sintaxis / Sintax
in_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.”

The comparison performed is case-sensitive, and it’s something to keep in mind. For example, "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 string needle will match an array value of 0 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 the strict flag to avoid unexpected behavior.

php.net

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.

Category: en-php
Something wrong? If you found an error or mistake in the content you can contact me on Twitter | @luisg2249_luis.
Last 4 post in same category

Comments