Jump to content

Why would this if/else statement not work?


Recommended Posts

I was working with something involving !=, which always manages to find some way to trip me up, but I'm finding this one odd and I'm wondering if one of you fine people can shed some light on it. This was the setup:

if (($thing != 0) && ($thing != "")) {echo "Hello";}

If $thing = 1, then this works.If $thing = 'taco', this does not work. But if $thing == 'taco', then obviously it doesn't equate to 0. The way I figured out a solution to this was by changing it to this:

if (($thing != "0") && ($thing != "")) {echo "Hello";}

With the 0 in quotation marks. Why did I have to do that? My guess is that if $thing is a string and my comparison is looking for an integer, that it borks it up somehow. But someone who knows would be nice. :)

Link to comment
Share on other sites

The reason why the 0 in quotation marks works is because you're basically saying: if the string 'taco' is not equal to the string '0', which turns out to be true because they are not equal strings. If you're looking to check if a variable contains a value in an if statement, you can do something like the following:

$thing = "taco"; if (($thing != NULL) && ($thing != "")){	 echo "Hello";}


$thing = "taco"; if (($thing != FALSE) && ($thing != "")){	 echo "Hello";}


$thing = "taco"; if (($thing !== 0) && ($thing != "")) // True if they are not of same type which they aren't, $thing is string, 0 is integer.{	 echo "Hello";}

or with the empty() function..

$thing = "taco"; if ((!empty($thing)) && ($thing != "")) {     echo "Hello";}

Edited by Don E
Link to comment
Share on other sites

it borks it up somehow
Interesting choice of words. Judge Robert Bork just died at the age of 85, he's the reason we have that term. He got screwed by the Senate during his confirmation hearings for the Supreme Court in 1987, and since then people who get rejected or have problems unfairly are said to get "borked".
  • Like 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Create New...