ZeroSuf3r
ZeroSuf3r

Reputation: 2001

if statement formatting

Basically, I always use words 'and' & 'or' so, my scripts look like:

if ($value == '1' or $value == '2' or $value == '3') {
    //do stuff
}


if ($value == '1' and $user_logged == 'Admin') {
    //do stuff
}
  1. It's possible get rid of of $value repeating?
  2. Any benefit in using and and or instead of || and && ?

Upvotes: 0

Views: 108

Answers (3)

Sjoerd
Sjoerd

Reputation: 75639

There is no way to shortcut expressions like

if ($value == 1 or 2 or 3) // invalid

But you can check the values in another way:

if (in_array($value, array(1, 2, 3))) {
    // do stuff
}

The difference between or and || is operator precedence. Use || and &&, not or and and.

Upvotes: 4

Mark Baker
Mark Baker

Reputation: 212452

Answer 1.

$inArray = (1,2,3);
if (in_array($value,$inArray)) {
    //  do stuff
}

Answer 2.

Operator precedence

Upvotes: 3

evilone
evilone

Reputation: 22740

You can use first if as a switch statement:

switch($value) {
   case "1":
      echo "value is 1";
      break;
   case "2":
      echo "value is 2";
      break;
   case "3":
      echo "value is 3";
      break;
}

Answer to your second question: Operator precedence

Upvotes: 1

Related Questions