Forum und email

in_array

(PHP 4, PHP 5)

in_array — Kontrollerer om en værdi findes i et array

Beskrivelse

bool in_array ( mixed $needle , array $haystack [, bool $strict ] )

Søger haystack igennem for needle og returnerer TRUE hvis værdien bliver fundet, og ellers FALSE.

Hvis den tredje parameter strict er sat til TRUE vil in_array() funktionen også tjekke for typen af needle i haystack .

Note: Hvis needle er en streng, bliver vil der blive taget forbehold for store og små bogstaver.

Note: I PHP versioner før 4.2.0 var needle ikke tilladt at være et array.

Example#1 in_array() eksempel

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

Den anden if-sætning slår fejl, fordi in_array() ser forskelligt på store og små bogstaver. Så overstående script vil vise dette:

Got Irix

Example#2 in_array() med strict eksempel

<?php
$a 
= array('1.10'12.41.13);

if (
in_array('12.4'$atrue)) {
    echo 
"'12.4' found with strict check\n";
}

if (
in_array(1.13$atrue)) {
    echo 
"1.13 found with strict check\n";
}
?>

Ovenstående eksempel vil udskrive:

1.13 found with strict check

Example#3 in_array() med et array som needle

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

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

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

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

Ovenstående eksempel vil udskrive:

  'ph' was found
  'o' was found

Se også array_search(), array_key_exists() og isset().