user2559062
user2559062

Reputation: 11

match a variable with at least one value in an array - php

I have one variable that comes from a database.
I then want to check whether that value is the same of one of the values in an array. If the variable matches one of the array values, then I want to print nothing, and if the variable does not match one of the array values, then I want to print something.
This is the code I have been trying without luck, I know that contains is not valid code, but that is the bit I cannot find any info for:

<?php
$site = getStuff(); 
$codes = array('value2', 'value4');
if ($codes contains $site)
{
echo "";
}
else
{
echo "something";
?>

So if the database would return value1 for $site, then the code should print "something" because value1 is not in the array.

Upvotes: 1

Views: 891

Answers (3)

Orangepill
Orangepill

Reputation: 24645

To provide another use way to do what the other answers suggest you can use a ternary if

echo in_array($site, $codes)?"":"something";

Upvotes: 0

bsoist
bsoist

Reputation: 785

if(!in_array($site,$codes)) {
    echo "something";
}

Upvotes: 1

apartridge
apartridge

Reputation: 1820

The function you are looking for is in_array.

if(in_array($site, array('value2', 'value4')))

Upvotes: 3

Related Questions