繁体   English   中英

如何检查数组是否包含 php 中的特定值?

[英]How can I check if an array contains a specific value in php?

我有一个 Array 类型的 PHP 变量,我想知道它是否包含特定值并让用户知道它在那里。 这是我的数组:

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

我想做类似的事情:

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

执行上述操作的最佳方法是什么?

使用in_array()函数

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

if (in_array('kitchen', $array)) {
    echo 'this array contains kitchen';
}
// 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

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));
    }
?>

您需要在阵列上使用搜索算法。 这取决于您的阵列有多大,您可以选择哪种使用方式。 或者,您可以使用以下内置函数:

http://www.w3schools.com/php/php_ref_array.asp

http://php.net/manual/zh/function.array-search.php

来自http://php.net/manual/en/function.in-array.php

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

除非设置严格,否则使用松散比较在干草堆中搜索针。

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

使用动态变量在数组中搜索

 /* 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";

以下是如何执行此操作:

<?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';
}

如果您想要一种快速的方法来使此搜索不区分大小写 ,请在此回复中查看建议的解决方案: https : //stackoverflow.com/a/30555568/8661779

资料来源: http//dwellupper.io/post/50/understanding-php-in-array-function-with-examples

$your_array=Array ( [0] => 厨房 [1] =>卧室 [2] =>living_room [3] =>dining_room); if(in_array('kitchen', $your_array)) {echo '这个数组包含厨房';}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM