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?
JavaScript Array includes() The includes() method returns true if an array contains a specified value. The includes() method returns false if the value is not found.
Answer: Use the PHP strpos() Function You can use the PHP strpos() function to check whether a string contains a specific word or not. The strpos() function returns the position of the first occurrence of a substring in a string.
PHP in_array() Function The in_array() function searches an array for a specific value. Note: If the search parameter is a string and the type parameter is set to TRUE, the search is case-sensitive.
The array_keys() function returns an array containing the keys.
Use the in_array()
function.
$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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With