How to check if a string is one of the known values?

<?php
$a = 'abc';

if($a among array('are','abc','xyz','lmn'))
    echo 'true';
?>

Suppose I have the code above, how to write the statement "if($a among...)"? Thank you


Use the in_array() function.

Manual says:

Searches haystack for needle using loose comparison unless strict is set.

Example:

<?php
$a = 'abc';

if (in_array($a, array('are','abc','xyz','lmn'))) {
    echo "Got abc";
}
?>

Like this:

if (in_array($a, array('are','abc','xyz','lmn')))
{
  echo 'True';
}

Also, although it's technically allowed to not use curly brackets in the example you gave, I'd highly recommend that you use them. If you were to come back later and add some more logic for when the condition is true, you might forget to add the curly brackets and thus ruin your code.


There is in_array function.

if(in_array($a, array('are','abc','xyz','lmn'), true)){
   echo 'true';
}

NOTE: You should set the 3rd parameter to true to use the strict compare.

in_array(0, array('are','abc','xyz','lmn')) will return true, this may not what you expected.