Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Abbreviate php if/or statement

Tags:

php

is there a way to abbreviate the following?

if ($chk == 1 || $chk == 3 || $chk == 5 || $chk == 7){
do some stuff
}

Thanks.

like image 772
Mr C Avatar asked Sep 07 '13 16:09

Mr C


People also ask

What is shorthand if else?

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.

Can I use ternary operator in PHP?

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.

Can we use if without else in PHP?

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.


2 Answers

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();
}
like image 200
Alex Shesterov Avatar answered Sep 30 '22 01:09

Alex Shesterov


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
    }
}
like image 24
Nicole Stutz Avatar answered Sep 29 '22 23:09

Nicole Stutz