Mazinfriki Mazinfriki - 4 months ago 9
PHP Question

IF statement with two conditions for the same variable

I'm trying to write an if sentence that checks if a variable accomplishes one of two given conditions.

What I was trying to evaluate is: "if the variable is bigger than 0 or the variable is equal to "more than one" then print its value.

Here's what I have:

$var="more than three";

if (($var == 'more than one') || ($var > '0')) {
echo "var is: " . $var;
}
// produces "var is more than three"

$var=0;

if (($var == 'more than one') || ($var > '0')) {
echo "var is: " . $var;
}
// produces "var is 0"


In both cases I'd expect no echo. What am I missing?

Answer

I'd suggest you to use typecasting here because you're dealing with integer as well as string types for $var.

Try this:

$var = "more than three";

if (((string)$var == 'more than one') || ((int)$var > 0))  {
  echo "var is: " . $var;
} 

$var = 0;
if (((string)$var == 'more than one') || ((int)$var > 0))  {
   echo "var is: " . $var;
}

You could use this as a reference: PHP Typecasting