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

Go To StackoverFlow.com

6

<?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

2012-04-04 07:55
by tuxnani


13

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";
}
?>
2012-04-04 07:57
by Bono
Don't forget that third closing parenthesis 'lmn')))wrydere 2014-03-14 16:52
Good spot! Edited i - Bono 2014-03-15 17:04


5

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.

2012-04-04 07:57
by MichaelRushton
+1 for the curly bracers advice - Strae 2012-04-04 11:31


2

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.

2012-04-04 07:58
by xdazz


1

Try this:

if (in_array($a, array('are','abc','xyz','lmn')))
{
  // Code
}

http://php.net/manual/en/function.in-array.php

in_arrayChecks if a value exists in an array

bool in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] ) Searches haystack for needle using loose comparison unless strict is set.

2012-04-04 08:00
by Dr.Kameleon
Ads