Как проверить, содержит ли массив определенное значение в php?

У меня есть переменная PHP типа Array, и я хотел бы узнать, содержит ли она определенное значение и позволяет пользователю узнать, что он есть. Это мой массив:

Array ( [0] => kitchen [1] => bedroom [2] => living_room [3] => dining_room) 

и я хотел бы сделать что-то вроде:

if(Array contains 'kitchen') {echo 'this array contains kitchen';}

Каков наилучший способ сделать это?

Ответ 1

Используйте in_array() функцию.

$array = array('kitchen', 'bedroom', 'living_room', 'dining_room');

if (in_array('kitchen', $array)) {
    echo 'this array contains kitchen';
}

Ответ 2

// Once upon a time there was a farmer

// He had multiple haystacks
$haystackOne = range(1, 10);
$haystackTwo = range(11, 20);
$haystackThree = range(21, 30);

// In one of these haystacks he lost a needle
$needle = rand(1, 30);

// He wanted to know in what haystack his needle was
// And so he programmed...
if (in_array($needle, $haystackOne)) {
    echo "The needle is in haystack one";
} elseif (in_array($needle, $haystackTwo)) {
    echo "The needle is in haystack two";
} elseif (in_array($needle, $haystackThree)) {
    echo "The needle is in haystack three";
}

// The farmer now knew where to find his needle
// And he lived happily ever after

Ответ 3

См. in_array

<?php
    $arr = array(0 => "kitchen", 1 => "bedroom", 2 => "living_room", 3 => "dining_room");    
    if (in_array("kitchen", $arr))
    {
        echo sprintf("'kitchen' is in '%s'", implode(', ', $arr));
    }
?>

Ответ 5

Из http://php.net/manual/en/function.in-array.php

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

Ищет стог сена для иглы, используя свободное сравнение, если не установлено строгое значение.

Ответ 6

if (in_array('kitchen', $rooms) ...

Ответ 7

Использование динамической переменной для поиска в массиве

 /* https://ideone.com/Pfb0Ou */

$array = array('kitchen', 'bedroom', 'living_room', 'dining_room');

/* variable search */
$search = 'living_room';

if (in_array($search, $array)) {
    echo "this array contains $search";
} else
    echo "this array NOT contains $search";

Ответ 8

Вот как вы можете это сделать:

<?php
$rooms = ['kitchen', 'bedroom', 'living_room', 'dining_room']; # this is your array
if(in_array('kitchen', $rooms)){
    echo 'this array contains kitchen';
}

Убедитесь, что вы ищете кухня, а не Кухня. Эта функция чувствительна к регистру. Таким образом, функция ниже просто не будет работать:

$rooms = ['kitchen', 'bedroom', 'living_room', 'dining_room']; # this is your array
if(in_array('KITCHEN', $rooms)){
    echo 'this array contains kitchen';
}

Если вы предпочитаете быстрый способ сделать этот поиск нечувствительным к регистру, взгляните на предлагаемое решение в этом ответе: fooobar.com/info/108125/...

Источник: http://dwellupper.io/post/50/understanding-php-in-array-function-with-examples