我如何检查数组是否包含特定的值在PHP?
我有一个types数组的PHPvariables,我想知道它是否包含一个特定的值,并让用户知道它在那里。 这是我的数组:
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)); } ?>
您需要在arrays上使用searchalgorithm。 这取决于你的arrays有多大,你有很多select使用什么。 或者你可以使用内build的function:
从http://php.net/manual/en/function.in-array.php
bool in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] )
除非严格设定,否则使用松散比较search大海捞针。
if (in_array('kitchen', $rooms) ...
使用dynamicvariables在数组中search
/* 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";