I have a PHP variable of type Array and I would like find out if it contains a specific value and let the user know that it is there. This is my array:
Array ( [0] => kitchen [1] => bedroom [2] => living_room [3] => dining_room)
and I would like do something like:
if(Array contains 'kitchen') {echo 'this array contains kitchen';}
What is the best way to do the above?
From http://php.net/manual/en/function.in-array.php
bool in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] )
Searches haystack for needle using loose comparison unless strict is set.
Using dynamic variable for search in array
/* 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";
See 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));
}
?>
You need to use a search algorithm on your array. It depends on how large is your array, you have plenty of choices on what to use. Or you can use on of the built in functions:
// 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
Following is how you can do this:
<?php
$rooms = ['kitchen', 'bedroom', 'living_room', 'dining_room']; # this is your array
if(in_array('kitchen', $rooms)){
echo 'this array contains kitchen';
}
Make sure that you search for kitchen and not Kitchen. This function is case sensitive. So, the below function simply won't work:
$rooms = ['kitchen', 'bedroom', 'living_room', 'dining_room']; # this is your array
if(in_array('KITCHEN', $rooms)){
echo 'this array contains kitchen';
}
If you rather want a quick way to make this search case insensitive, have a look at the proposed solution in this reply: https://stackoverflow.com/a/30555568/8661779
Source: http://dwellupper.io/post/50/understanding-php-in-array-function-with-examples
if (in_array('kitchen', $rooms) ...
Source: Stackoverflow.com