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

前端 未结 4 2013
长发绾君心
长发绾君心 2020-12-03 14:49

Suppose I have the code above, how to write th

相关标签:
4条回答
  • 2020-12-03 15:39

    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.

    0 讨论(0)
  • 2020-12-03 15:39

    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.

    0 讨论(0)
  • 2020-12-03 15:49

    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";
    }
    ?>
    
    0 讨论(0)
  • 2020-12-03 15:50

    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.

    0 讨论(0)
提交回复
热议问题