Norman
Norman

Reputation: 6365

Php check if 5 variables are the same value

In php I need to check if 5 variables are the same value, and then proceed.

Instead of doing

if($a == 'logged' && $b == 'logged' && $c == 'logged' && $d == 'logged' && $e == 'logged') 
{ 
   // Code to run here
}

Is there a different way to do it? Like:

if($a,$b,$c,$d == 'logged')

Something like that possible..?

Upvotes: 0

Views: 846

Answers (2)

arkascha
arkascha

Reputation: 42915

I recommend against trying to shorten that. There is no more compact notation available to my knowledge apart from optical effects, none that the php parser accepts. The efficiency would not be better, since internally the same comparisons have to be done anyway.

Instead I usually try to enhance the readability of the code instead and use reversed notation, since human time is much more expensive than computer power these days :-)

if (   'logged' == $a 
    && 'logged' == $b
    && 'logged' == $c 
    && 'logged' == $d 
    && 'logged' == $e )  { 
  // Code
}

Upvotes: 2

Jérôme
Jérôme

Reputation: 292

You can use something like this

$values = array($a, $b, $c, $d, 'logged');

if(count(array_unique($values)) === 1) {
    //All elements are the same
}

Upvotes: 9

Related Questions