0

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..?

8
  • 1
    not sure but could $a == $b == $c == $d == $e == 'logged' this work Commented Apr 30, 2014 at 12:00
  • @kpp: Parse error: syntax error, unexpected '==' (T_IS_EQUAL) Commented Apr 30, 2014 at 12:02
  • I wonder why it does not work? Commented Apr 30, 2014 at 12:05
  • @kpp before writing it as a comment, you could test it yourself and see... Commented Apr 30, 2014 at 12:06
  • 1
    if (($a == $b) == ($c == "logged")) { echo "yup"; } this worked for me Commented Apr 30, 2014 at 12:07

2 Answers 2

9

You can use something like this

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

if(count(array_unique($values)) === 1) {
    //All elements are the same
}
Sign up to request clarification or add additional context in comments.

12 Comments

This is elegant, but much less efficient and hard to read / understand / debug. But a really interesting idea!
@arkascha this could be wrapped into helper function with proper name, so the coder will know what it's doing :)
@RoyalBg Yep, that is true indeed. But: that makes this even less efficient, besides having to create an array on-the-fly then also a function call has to be done.
@arkascha not true at all: function compareValues($value) { return count(array_unique(func_get_args()))==1; } so you can pass $a = 'asd'; $b = 'asd'; $c = 'asd'; var_dump(compareValues('asd', $a, $b, $c));
Sorry, I don't get your point here. That version is different from your answer above, but is has similar problems. Just that now you don't create an array and call a function, now you call four functions, which is even less efficient! Function calls are really expensive.
|
2

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
}

1 Comment

Although this might be good advice, it's really not an answer of the question, so it should not be posted as an answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.