is there a way to abbreviate the following?
if ($chk == 1 || $chk == 3 || $chk == 5 || $chk == 7){
do some stuff
}
Thanks.
Else (Ternary Operator) There is also a short-hand if else, which is known as the ternary operator because it consists of three operands. It can be used to replace multiple lines of code with a single line.
The term "ternary operator" refers to an operator that operates on three operands. An operand is a concept that refers to the parts of an expression that it needs. The ternary operator in PHP is the only one that needs three operands: a condition, a true result, and a false result.
An if statement looks at any and every thing in the parentheses and if true, executes block of code that follows. If you require code to run only when the statement returns true (and do nothing else if false) then an else statement is not needed.
if (in_array($chk, array(1, 3, 5, 7))) ...
Or, if you plan to include if-elseif-cascades, use switch statement:
switch($chk)
{
case 1: case 3: case 5: case 7:
do_something();
break;
case 10: case 30: case 50: case 70:
do_something_else();
break;
default:
do_default();
}
If you use only uneven numbers, you could check the value. If the value is uneven, then the function will be executed
$unevenNumbers=array(1,2,3,4,5,7);
foreach($unevenNumbers as $nbr){
if( $nbr % 2 !== 0){
//do some stuff
}
}
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