PHP: verificare se un elemento esiste in un array lineare

PHP: verificare se un elemento esiste in un array lineare

In PHP esiste una funzione specifica per verificare se un elemento esiste in un array lineare.

La funzione è in_array(elemento, array, strict = false) e restituisce un valore booleano. Esempio d'uso:

$arr = ['a', 1, 'b', 2];
$is_a = in_array('a', $arr); // true
$is_c = in_array('c', $arr); // false

Il terzo parametro di questa funzione è opzionale e indica se la verifica debba tener conto o meno della coerenza tra il tipo di dati dell'elemento da cercare e quello degli elementi presenti nell'array. La documentazione aggiunge questa nota:

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 undesireable 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.

Quindi avremo ad esempio:

$arr = ['a', 1, 'b', 2];
$is_num = in_array('1', $arr, true); // false

'1' (stringa) e 1 (intero) non sono dello stesso tipo di dati, quindi la verifica restituirà false.

Torna su