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 post
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";}

or...

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

or..

$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 post
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 post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...