in_array

(PHP 4, PHP 5)

in_array — Проверить, присутствует ли в массиве значение

Описание

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

Ищет в haystack значение needle и возвращает TRUE в случае удачи, FALSE в противном случае.

Если третий параметр strict установлен в TRUE тогда функция in_array() также проверит соответствие types параметра needle и соответствующего значения массива haystack .

Замечание: Если needle - строка, сравнение будет регистрозависмым.

Замечание: В PHP версий, более ранних, чем 4.2.0 параметр needle не может быть массивом.

Пример #1 Пример использования in_array()

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

Второго совпадения не будет, потому что in_array() регистрозависима, таким образом, программа выведет:

Got Irix

Пример #2 Пример использования in_array() с параметром strict

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

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

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

Результат выполнения данного примера:

1.13 found with strict check

Пример #3 Пример использования in_array() с массивом в качестве параметра needle

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

if (
in_array(array('p''h'), $a)) {
    echo 
"'ph' найдено
"
;
}

if (
in_array(array('f''i'), $a)) {
    echo 
"'fi' найдено
"
;
}

if (
in_array('o'$a)) {
    echo 
"'o' найдено
"
;
}
?>

Результат выполнения данного примера:

  'ph' найдено
  'o' найдено

См. также array_search(), array_key_exists() и isset().

Коментарии

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$haystacktrue) ? '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.
2009-01-17 15:05:03
http://php5.kiev.ua/manual/ru/function.in-array.html
If you're creating an array yourself and then using in_array to search it, consider setting the keys of the array and using isset instead since it's much faster.

<?php

$slow 
= array('apple''banana''orange');

if (
in_array('banana'$slow))
    print(
'Found it!');

$fast = array('apple' => 'apple''banana' => 'banana''orange' => 'orange');

if (isset(
$fast['banana']))
    print(
'Found it!');

?>
2009-10-05 03:53:45
http://php5.kiev.ua/manual/ru/function.in-array.html
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$arraytrue); // true
in_array(false$arraytrue); // true
in_array(765$arraytrue); // true
in_array(763$arraytrue); // false
in_array('egg'$arraytrue); // false
in_array('hhh'$arraytrue); // false
in_array(array(), $arraytrue); // false

?>
2011-10-27 06:35:27
http://php5.kiev.ua/manual/ru/function.in-array.html
Автор:
$a = new StdClass();
$b = new StdClass();

// Expected: false, got: true
var_dump(in_array($a, [$b]));
// bool(true)

// Works fine
var_dump(in_array($a, [$b], true));
// bool(false)
2022-11-01 16:46:20
http://php5.kiev.ua/manual/ru/function.in-array.html
Автор:
$a = new StdClass();
$b = new StdClass();

// Expected: false, got: true
var_dump(in_array($a, [$b]));
// bool(true)

// Works fine
var_dump(in_array($a, [$b], true));
// bool(false)
2022-11-01 16:46:20
http://php5.kiev.ua/manual/ru/function.in-array.html
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.
2022-11-08 12:26:51
http://php5.kiev.ua/manual/ru/function.in-array.html
Автор:
I'd like to point out that, if you're using Enum data structures and want to compare whether an array of strings has a certain string Enum in it, you need to cast it to a string.

From what I've tested, the function works correctly:
if the array is filled with strings and you're searching for a string;
if the array is filled with Enums and you're searching for an Enum.
2023-02-14 12:45:29
http://php5.kiev.ua/manual/ru/function.in-array.html
Автор:
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$arraytrue); // bool(false)
$hasNumber in_array_recursive(7$arraytrue); // bool(true)

function in_array_recursive(mixed $needle, array $haystackbool $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;
}
2023-06-09 13:04:01
http://php5.kiev.ua/manual/ru/function.in-array.html

    Поддержать сайт на родительском проекте КГБ