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 expression "if ($ a among ...)"? Thanks you

+6
source share
4 answers

Use in_array() .

The manual says:

Searches for a haystack for a needle using a free comparison, unless a strict value is set.

Example:

 <?php $a = 'abc'; if (in_array($a, array('are','abc','xyz','lmn'))) { echo "Got abc"; } ?> 
+12
source

Like this:

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

In addition, although it is technically permitted not to use braces in the example you gave, I highly recommend that you use them. If you come back later and add some more logic when the condition is true, you may forget to add curly braces and thereby ruin your code.

+5
source

There is an in_array function.

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

Note: You must set the 3rd parameter to true order to use strict comparison.

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

+2
source

Try the following:

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

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

in_array - Checks if a value exists in an array

bool in_array (mixed $ needle, array $ haystack [, bool $ strict = FALSE]) Searches for a haystack for the needle using free comparison, if Strictly specified.

+1
source

Source: https://habr.com/ru/post/912364/


All Articles