I have a variable$var
.
I want echo "true"
if $var
is equal to any of the following values abc
, def
, hij
, klm
, or nop
. Is there a way to do this with a single statement like &&
??
PHP Conditional Statements if statement - executes some code if one condition is true. if...else statement - executes some code if a condition is true and another code if that condition is false. if... elseif...else statement - executes different codes for more than two conditions.
The multiple IF conditions in Excel are IF statements contained within another IF statement. They are used to test multiple conditions simultaneously and return distinct values. The additional IF statements can be included in the “value if true” and “value if false” arguments of a standard IF formula.
The nested if statement contains the if block inside another if block. The inner if statement executes only when specified condition in outer if statement is true.
An elegant way is building an array on the fly and using in_array()
:
if (in_array($var, array("abc", "def", "ghi")))
The switch
statement is also an alternative:
switch ($var) {
case "abc":
case "def":
case "hij":
echo "yes";
break;
default:
echo "no";
}
if($var == "abc" || $var == "def" || ...)
{
echo "true";
}
Using "Or" instead of "And" would help here, i think
you can use in_array function of php
$array=array('abc', 'def', 'hij', 'klm', 'nop');
if (in_array($val,$array))
{
echo 'Value found';
}
Dont know, why you want to use &&
. Theres an easier solution
echo in_array($var, array('abc', 'def', 'hij', 'klm', 'nop'))
? 'yes'
: 'no';
you can use the boolean operator or: ||
if($var == 'abc' || $var == 'def' || $var == 'hij' || $var == 'klm' || $var == 'nop'){
echo "true";
}
I found this method worked for me:
$thisproduct = "my_product_id";
$array=array("$product1", "$product2", "$product3", "$product4");
if (in_array($thisproduct,$array)) {
echo "Product found";
}
You can try this:
<?php
echo (($var=='abc' || $var=='def' || $var=='hij' || $var=='klm' || $var=='nop') ? "true" : "false");
?>
Sorry to resurrect this, but I stumbled across it & believe it adds value to the question.
In PHP 8.0.0^ you can now use the match expression like so:
<?php
echo match ($var) {
'abc','def','hij','klm' => 'true',
};
?>
//echos 'true' as a string
Working link from OnlinePHPfunctions
PHP Manual
Try this piece of code:
$first = $string[0];
if($first == 'A' || $first == 'E' || $first == 'I' || $first == 'O' || $first == 'U') {
$v='starts with vowel';
}
else {
$v='does not start with vowel';
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With