Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

php

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?

like image 779
hairynuggets Avatar asked Jan 16 '12 14:01

hairynuggets


People also ask

How do you check if an array contains a specific value?

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.

How do you check if a array contains a specific word in PHP?

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.

What is in_array function in PHP?

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.

What is array_keys () used for in PHP?

The array_keys() function returns an array containing the keys.


2 Answers

Use the in_array() function.

$array = array('kitchen', 'bedroom', 'living_room', 'dining_room');  if (in_array('kitchen', $array)) {     echo 'this array contains kitchen'; } 
like image 137
Wiseguy Avatar answered Oct 20 '22 01:10

Wiseguy


// 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 
like image 26
Peter Avatar answered Oct 19 '22 23:10

Peter