1

I would expect the last if-statement to be true, but it echos out: $var is type, max or min.

Can anybody explain what exactly is happening? Because I don't understand.

$var = 'required'; if($var == 'unique') { echo '$var is unique.'; } else if($var == ('type' || 'max' || 'min')) { echo '$var is type, max or min.'; } else if($var == 'required') { echo '$var is required.'; } 

6 Answers 6

11

You won't be able to use || like this. The proper way would be:

if ($var == 'type' || $var == 'max' || $var == 'min') 

If there are more arguments to check, consider using in_array instead, it'll make the check more concise:

if (in_array($var, ['type', 'max', 'min', 'some', 'other', 'string', 'to', 'check'])) 
Sign up to request clarification or add additional context in comments.

Comments

2

That's because ('type' || 'max' || 'min') is an expression that evaluates to boolean true, which means you're asking PHP to evaluate ($var == true). Since it's not empty or null, the expression is true. Change it to:

if ($var == 'type' || $var == 'max' || $var == 'min') 

Comments

2

What is happening here is that php is first evaluating ('type' || 'max' || 'min'). This evaluation is true. Afterwards the comparison of 'required' and true is being evaluted to true. This happens because when comparing a boolean to a string, the string is casted as true unless the string is 0. Referring to this table of comparison results may prove helpful https://www.php.net/manual/en/types.comparisons.php.

You want:

$var = 'required'; if($var == 'unique') { echo '$var is unique.'; } else if($var == 'type' || $var == 'max' || $var == 'min') { echo '$var is type, max or min.'; } else if($var == 'required') { echo '$var is required.'; } 

I would even suggest doing === to make sure it does an absolute string comparison in case $var is ever passed in as a boolean or another type.

$var = 'required'; if($var === 'unique') { echo '$var is unique.'; } else if($var === 'type' || $var === 'max' || $var === 'min') { echo '$var is type, max or min.'; } else if($var === 'required') { echo '$var is required.'; } 

Comments

1
($var == ('type' || 'max' || 'min')) 

You can't write like this. You shoul write it

($var == 'type' || $var == 'max' || $var == 'min')) 

Comments

1

Try this out:

$var = 'required'; if($var == 'unique') { echo '$var is unique.'; } else if($var == 'type' || $var == 'max' || $var == 'min')) { echo '$var is type, max or min.'; } else if($var == 'required') { echo '$var is required.'; } 

Comments

0

the correct way is:

if($var=='type'||$var=='max'||$var=='min') 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.