Start · Sprachen · PHP · Referenz · in_array

in_array

Funktion

Prüft, ob ein Wert in einem Array vorkommt. <strong>Immer</strong> mit <code>$strict = true</code>.

seit PHP 4.0.0 Kategorie: array

Signatur

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

Beschreibung

Ohne strict: in_array(0, ['a', 'b'], false) gibt true zurück — weil 0 == 'a' vor PHP 8. Type-Juggling-Falle!

Parameter

Name Typ Default Beschreibung
$needle Pflicht mixed Suchwert.
$haystack Pflicht array Array.
$strict bool false Strikter Vergleich.

Rückgabewert

Typ
bool
Beschreibung
true wenn vorhanden.

Beispiele

Rollen-Check

<?php

if (in_array($role, ['admin', 'editor'], true)) {
    // erlaubt
}

// Wichtig · Fallstricke

Immer strict: Ohne den dritten Parameter macht PHP loose comparison — Quelle vieler subtiler Bugs.