0

is there a shorthand version of checking if numerous variables have the same value please ?

instead of :-

if ($a="valid") {do stuff;} if ($b="valid") {do stuff;} if ($c="valid") {do stuff;} if ($d="valid") {do stuff;} 

is there something like:-

if ($a or $b or $c or $d = "valid") {do stuff;} 
2
  • is that a typo or you assigning values inside IF statements? If so, if($a = $b = $c = 'valid')... lol Commented Feb 8, 2014 at 14:26
  • typo :D ... should be if($a=="valid") ... my bad Commented Feb 8, 2014 at 14:40

5 Answers 5

8

Just put all of the variables you want to check into an array and use in_array() to check them all at once:

if (in_array('valid', array($a, $b, $c, $d))) { do stuff; } 
Sign up to request clarification or add additional context in comments.

Comments

3

John Conde's solution of putting together an array and then using in_array is a good solution. In case you want to stick with basic string comparisons, somewhat like in your example code, then you could do:

if ($a == 'valid' or $b == 'valid' or $c == 'valid' or $d == 'valid') { // DO STUFF } 

Something to keep in mind, based on what I noticed from your example code: When doing comparisons for equality in PHP, use == and not =. The single = is for assignment, while the double == is for comparison.

2 Comments

thanks guys ... i am using this style, because i am actually using <> rather than ==
@Blackwolf - glad I could help. Thanks for accepting my answer. I'm still going to upvote John Conde's solution though - it's a good one.
1

You could extract a function doing the comparison and have :

if (check($a) || check($b) ...) 

It's not as sexy as John proposition (whatever his girlfriend says) I have to admit.

Comments

1

if ($a == 'valid' || $b == 'valid' || $c == 'valid' || $d == 'valid') { // DO STUFF }

This would be best because if first condition is true then no need to check rest.

Comments

0

Yes you can, like this:

if (($a || $b || $c || $d) == "valid") 

6 Comments

correct me if i am wrong, but this would seem to be AND rather than OR though
I don't have it, this mean ("aaa" && "bbb" && "valid") would be equal to "valid" ? But also "aaa" and "bbb" ?
@Craftein - I think you never knew this is possible... because this is not possible. && is the logical AND operator. If you do $a && $b && $c && $d, you'll either get true or false - you will never get a string with value "valid". If you use the || logical OR operator for - you'll still run into the same issue.
okay, crap tastic. none work on my local machine, you sure it's right? @AlvinLee yeah. just noticed it now. | or || didn't work for OP's question. funny thing is, if OP's req is all the same, & should have worked.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.