phpday 2027 - Call for Papers

in_array

(PHP 4, PHP 5, PHP 7, PHP 8)

in_array — Controlla se un valore esiste in un array

Descrizione

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

Cerca needle in haystack usando il confronto debole, a meno che non sia impostato strict.

Elenco dei parametri

needle

Il valore cercato.

Nota:

Se needle è una stringa, il confronto viene effettuato distinguendo tra maiuscole e minuscole.

haystack

L'array.

strict

Se il terzo parametro strict è impostato a true, la funzione in_array() controllerà anche i tipi di needle in haystack.

Nota:

Prima di PHP 8.0.0, una string non numerica come needle corrispondeva in modo debole a un valore 0 in haystack, e viceversa. A partire da PHP 8.0.0, il numero viene convertito in string e i due vengono confrontati come stringhe, quindi corrisponde solo una string numerica con lo stesso valore.

La modalità non stretta usa comunque il confronto debole, quindi valori di tipi diversi possono comunque risultare uguali: true corrisponde a qualsiasi string che equivale a vero, e false corrisponde sia a "" che a "0". A meno che i tipi di tutti i valori coinvolti non siano noti con certezza, passare sempre strict per forzare un confronto di identità.

Valori restituiti

Restituisce true se needle viene trovato nell'array, altrimenti false.

Esempi

Example #1 Esempio di in_array()

<?php
$os = array("Mac", "NT", "Irix", "Linux");
if (in_array("Irix", $os)) {
    echo "Trovato Irix";
}
if (in_array("mac", $os)) {
    echo "Trovato mac";
}
?>

La seconda condizione non è soddisfatta perché in_array() distingue tra maiuscole e minuscole, quindi il programma precedente visualizzerà:

Trovato Irix

Example #2 Esempio di in_array() con strict

<?php
$a = array('1.10', 12.4, 1.13);

if (in_array('12.4', $a, true)) {
    echo "'12.4' trovato con il controllo stretto\n";
}

if (in_array(1.13, $a, true)) {
    echo "1.13 trovato con il controllo stretto\n";
}
?>

Il precedente esempio visualizzerà:

1.13 trovato con il controllo stretto

Example #3 in_array() con un array come needle

<?php
$a = array(array('p', 'h'), array('p', 'r'), 'o');

if (in_array(array('p', 'h'), $a)) {
    echo "'ph' trovato\n";
}

if (in_array(array('f', 'i'), $a)) {
    echo "'fi' trovato\n";
}

if (in_array('o', $a)) {
    echo "'o' trovato\n";
}
?>

Il precedente esempio visualizzerà:

'ph' trovato
'o' trovato

Vedere anche:

  • array_search() - Cerca un valore in un array e, se lo trova, restituisce la prima chiave corrispondente
  • isset() - Verifica se una variabile è dichiarata ed è diversa da null
  • array_key_exists() - Controlla se la chiave o l'indice specificato esiste nell'array

User Contributed Notes 6 notes

up
419
beingmrkenny at gmail dot com
15 years ago
Loose checking returns some crazy, counter-intuitive results when used with certain arrays. It is completely correct behaviour, due to PHP's leniency on variable types, but in "real-life" is almost useless.

The solution is to use the strict checking option.

<?php

// Example array

$array = array(
    'egg' => true,
    'cheese' => false,
    'hair' => 765,
    'goblins' => null,
    'ogres' => 'no ogres allowed in this array'
);

// Loose checking -- return values are in comments

// First three make sense, last four do not

in_array(null, $array); // true
in_array(false, $array); // true
in_array(765, $array); // true
in_array(763, $array); // true
in_array('egg', $array); // true
in_array('hhh', $array); // true
in_array(array(), $array); // true

// Strict checking

in_array(null, $array, true); // true
in_array(false, $array, true); // true
in_array(765, $array, true); // true
in_array(763, $array, true); // false
in_array('egg', $array, true); // false
in_array('hhh', $array, true); // false
in_array(array(), $array, true); // false

?>
up
4
Julian Sawicki
3 years ago
Here is a recursive in_array function: 

<?php

$myNumbers = [
    [1,2,3,4,5],
    [6,7,8,9,10],
];

$array = [
    'numbers' => $myNumbers
];

// Let's try to find number 7 within $array
$hasNumber = in_array(7, $array, true); // bool(false)
$hasNumber = in_array_recursive(7, $array, true); // bool(true)

function in_array_recursive(mixed $needle, array $haystack, bool $strict): bool
{
    foreach ($haystack as $element) {
        if ($element === $needle) {
            return true;
        }

        $isFound = false;
        if (is_array($element)) {
            $isFound = in_array_recursive($needle, $element, $strict);
        }
        
        if ($isFound === true) {
            return true;
        }
    }

    return false;
}
up
4
leonhard dot radonic+phpnet at gmail dot com
4 years ago
I got an unexpected behavior working with in_array. I'm using following code:

<?php
// ...
$someId = getSomeId(); // it gets generated/fetched by another service, so I don't know what value it will have. P.S.: it's an integer

// The actual data in my edge-case scenario:
// $someId = 0;
// $anyArray = ['dataOne', 'dataTwo'];
if (in_array($someId, $anyArray)) {
    // do some work
}
// ...
?>

With PHP7.4, in_array returns boolean true.
With PHP8.1, in_array returns boolean false.

It took me quite some time to find out what's going on.
up
9
rhill at xenu-directory dot net
17 years ago
I found out that in_array will *not* find an associative array within a haystack of associative arrays in strict mode if the keys were not generated in the *same order*:

<?php

$needle = array(
    'fruit'=>'banana', 'vegetable'=>'carrot'
    );

$haystack = array(
    array('vegetable'=>'carrot', 'fruit'=>'banana'),
    array('fruit'=>'apple', 'vegetable'=>'celery')
    );

echo in_array($needle, $haystack, true) ? 'true' : 'false';
// Output is 'false'

echo in_array($needle, $haystack) ? 'true' : 'false';
// Output is 'true'

?>

I had wrongly assumed the order of the items in an associative array were irrelevant, regardless of whether 'strict' is TRUE or FALSE: The order is irrelevant *only* if not in strict mode.
up
1
upadrian at gmail dot com
9 months ago
It's worth the notice that in_array is case-sensitive.
Apart from the very first option of make all lowercase or uppercase, and then compare, I found this elegant solution:

<?php

function in_arrayi(float|int|string $needle, array $haystack):bool {
    return (bool)array_uintersect([$needle],$haystack,strcasecmp(...));
}

$needle = "abc";
$haystack = ["Abc","deF","gHi"];
$result = in_arrayi($needle,$haystack);

var_dump($result);

?>
up
0
eurorusty at yahoo dot ca
2 years ago
I'm not sure why PHP doesn't provide a way to specify a binary search. Here's an example of the performance gains, for this array size, about 50x improvement using interpreted PHP. If built in, it could probably achieve around 1000x improvement, again for this array size.

<?php

// Set up sorted array
$X = array(1);
for ($j = 1; $j < 50000; ++$j)
    $X[] = $X[$j - 1] + rand(1, 6);

// Using in_array
$x = -microtime(true);
$m = 0;
for ($j = 0; $j < 10000; ++$j)
    $m += in_array(rand(1, 175000), $X);
$x += microtime(true);
echo $x.PHP_EOL;

// Using binarySearch
$x = -microtime(true);
$m = 0;
for ($j = 0; $j < 10000; ++$j)
    $m += binarySearch($X, rand(1, 175000));
$x += microtime(true);
echo $x.PHP_EOL;

function binarySearch($array, $value) {
    $low = 0;
    $high = count($array) - 1;
    while ($low <= $high) {
        $pivot = floor(($low + $high) / 2);
        if ($array[$pivot] == $value)
            return true;
        if ($value < $array[$pivot])
            $high = $pivot - 1;
        else
            $low = $pivot + 1;
    }
    // No match
    return false;
}

/* Sample outputs, first is in_array, second is binarySearch
1.3544600009918
0.026464939117432

1.6158990859985
0.033976078033447

1.5184400081635
0.026461124420166
*/
Adding new notes is disabled. Please see the links in the Found A Problem? section.
To Top