How to Check If an Array Contains a Specific Value in PHP

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

Use the in_array() function.

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

if (in_array('kitchen', $array)) {
echo 'this array contains kitchen';
}

How to determine if an array contains anything but a specific value?

TBH - I think your current version is the most optimal. It will potentially only involve 1 test, find a difference and then return.

The other solutions (so far) will always process the entire array and then check if the result is empty. So they will always process every element.

You should add a return FALSE though to make the function correct.

php check if a specific value in array contains value bigger than 0

You can iterate on your array and stop it when you have what you search:

$contains = false;
foreach(json_decode($json_data, true) as $item){
if ($item['value']) {
$contains = true;
break;
}
}

You can achieve that in many ways. But that can help you to go further.

Check if string contains a value in array

Try this.

$string = 'my domain name is website3.com';
foreach ($owned_urls as $url) {
//if (strstr($string, $url)) { // mine version
if (strpos($string, $url) !== FALSE) { // Yoshi version
echo "Match found";
return true;
}
}
echo "Not found!";
return false;

Use stristr() or stripos() if you want to check case-insensitive.

How to check if an array value exists?

Using the instruction if?

if(isset($something['say']) && $something['say'] === 'bla') {
// do something
}

By the way, you are assigning a value with the key say twice, hence your array will result in an array with only one value.

How to check if an associative array contains a value and only that value?

$hasOnlySingleChoice = true;
foreach ($array as $item) {
if ($item['choice'] !== 'Afhalen') {
$hasOnlySingleChoice = false;
break;
}
}

PHP - If array contains

Create one image for each language on a folder containing the language code, like so

images/en-flag.png
images/nl-flag.png

And loop thru the array to display the images

foreach ($languagevalue as $lang) {
echo '<img src="images/' . $lang . '-flag.png" alt="Sample Image"/>';
}


Related Topics



Leave a reply



Submit