Syndicate

Feed

True or false in php

I thought I knew what qualified as a false statement in php. I thought that any undefined variable, or any integer or float value equal to 0, was false, and believed that everything else was true. I was wrong. This article serves two purposes : the least of them is to inform you, because you probably know better than I do, while the principal aim is for me to play with Javascript in Drupal... because I have prepared an interactive challenge for you.

Let’s begin by examining sample code.

// some variables...
$myFirstArray = array();
$myFirstString = '';
$mySecondArray = array();
$mySecondArray['score'] = '0%';

The variable $myFirstArray is an empty array. It is ready to have elements added to it, but it is currently empty. We can print the content of an empty array, using the function print_r($myFirstArray) between <pre> tags. That would be a valid call. Let’s do that.

Array
(
)

We can also use the all-purpose function empty() to check whether our array (or any array) is empty or not : empty($myFirstArray) will return true. The array is set, and we have not assigned a NULL value to it, so isset($myFirstArray) returns true as well.

The variable $myFirstString is an empty string. It contains no characters, not even a space, which is a character in its own right. What you’re seeing on the right of the assignment operator is a pair of single quotes :

$myFirstString = '';

Just like the empty array :

  • $myFirstString is set, i.e. isset($myFirstString) returns true.
  • $myFirstString is empty, i.e. empty($myFirstString) returns true.

Both variables are false, though.

if ($myFirstArray || $myFirstString) {
  print "You’ll never see these words in our current state of affairs.";
}

The associative array $mySecondArray is not empty. It contains 1 element, a string, with value '0%', and that value is associated to the key 'score' :

$mySecondArray = array();
$mySecondArray['score'] = '0%';

May that element be referenced using $mySecondArray[0] ? In other words, will the following condition evaluate to true ?

if ($mySecondArray[0]) {
  print "You will never see these words.";
}

It won’t. Assigning a value to $mySecondArray['score'], when the array was previously empty, is not the same as assigning a value to $mySecondArray[0].

Array
(
    [score] => 0%
)

Let us change the content of this array. Let’s say the score is zero as in the character '0' instead of '0%' :

Array
(
    [score] => 0
)

$mySecondArray['score'] = '0';
if ($mySecondArray['score']) {
  print "You will never see these words.";
}

Although isset($mySecondArray['score']) is true, $mySecondArray['score'] will return false because the string '0' evaluates to false in php.

The integer 0 is false (that much I knew), the float 0.000 is false too, that makes sense. And the character '0' is false as well.

What if we declared a variable and assigned a NULL value to it, would that variable be false ?

$myVar = NULL;
if (isset($myVar) || $myVar) {
  print "You will never see these words.";
}

The variable has been set, hence isset($myVar) should return true but it returns false. In PHP, assigning a NULL value to a variable is “like” unsetting it.

We’re also observing that the variable $myVar evaluates to false, in the conditional statement. That’s because NULL, in a conditional statement, evaluates to false. Confused ?

PHP.net goes about listing what is false in php (follow this link). From that list, we can figure out what is true because that will be anything else. When using a conditional statement, all these values are false :

  • The special type NULL and the boolean FALSE — and these keywords are case-insensitive.
  • The integer 0, the float 0.00 or the string (or character) '0' (or "0").
  • An empty string : ''.
  • An array with zero element.
  • An object with zero member variables.

Are you ready for the challenge, now ?

Determine whether each expression is true or false, then check your score. You can change your selections and re-calculate your score at any time.

The truth in php challenge
'0 times' + 'zero'  
'0.00'  
True  
'1.5 cups' - '3 cups' / 2  
0 === FALSE  
2 == TRUE  
0.0  
empty($declaredForTheFirstTime)  
true || FALSE  
$myArray[] = '0'  

    

Summary

  1. All numerical values are true, whether they are integers or floats, positive or negative, EXCEPT 0 and 0.0, which are false.

  2. The string (or character) '0' is false, but '0.0' is true.

  3. The keywords TRUE, FALSE and NULL are case-insensitive.

    “Best practices” in PHP prefer that we use capital letters for these keywords, but it really is up to me — and you.

  4. In a conditional statement, conditions are evaluated from left to right. In the case where we have if(condition1 && condition2 && condition3...), if the first condition is false, the second condition is not evaluated. For this reason, it is wise to order the conditions so that the condition most likely false (or strict) is put first, and the most processing-intensive condition is put last.

    In a conditional statement of the form condition1 || condition2 || condition3... , if the first condition is true, then the second condition is not evaluated.

    That behavior has been coined short-circuit evaluation. PHP, like any other programming language, is efficient, hence stops evaluating a logical expression as soon as the result is determined.

  5. When arithmetic operators, such as +, -, /, *, are used with strings, the php engine tries to convert the strings into numbers, then it performs the calculation. The expression '1.5 cups' - '3 cups' / 2 becomes 1.5 - 3 / 2. The division has precedence, hence it is evaluated first. The result of that division is a floating-point number : 1.5. That value is substracted from 1.5 and the result is 0.0. And 0.0 is false. If a string does not begin with a number, it is converted to the integer 0 (zero). Hence, the expression '0 times' + 'zero' becomes 0 + 0 which equals to 0.

    It is in Javascript that the "+" operator becomes a concatenator operator when used with strings. In php, the "+" is always an arithmetic operator, and the concatenator operator is the dot, i.e. ".".

  6. For the expression value1 === value2 to be true, value1 and value2 must not only have the same value but be of the same data type. The expression 2 == TRUE is true because if we convert 2 to a boolean, 2 is true. However, 2 === TRUE is false because 2 is an integer and true is a boolean. The expression 2 === 2.0 is also false, while 2 == 2.0 is true. The expression 0 === FALSE is also false, while 0 == FALSE is true.

    "===" is called the identity comparison operator.

    We often use this operator with the php function strpos(). The return value of strpos(string haystack, string needle) is the first position in the haystack at which the substring (the needle) is found. The return value is 0 if the needle is at the beginning of the haystack, and it is FALSE if the needle is not in the haystack.

    // A common test
    $needle = "lover";
    $haystack = "clovers";
    if (strpos($haystack, $needle) !== FALSE) {
      print "The needle is in the haystack.";
    }

[]

This tutorial was helpful to you? Post a comment and/or donate. Thank you.

Last edited by Caroline Schnapp about 3 years ago.

Comments

Cool. I learned something

Cool. I learned something today. Thanks.

Seems to me PHP is trying to

Seems to me PHP is trying to be too clever for it's own good. Especially in evaluating (string) 0 as false.

Means to check whether a variable contains a zero length string, you have to do if(strlen($string)) or if(empty($string)) instead of just if($string).

And if your going to evaluate (string)(int) 0 to false, why not (string)(float) 0.00.

It's just one more annoying thing you have to remember.

hi caroline and thanks

just a quick comment to say hello-
and thanks for this post.

as usual you are doing great things-

and most especially sharing your work and insights
with others through your posts-

which are filled with charm, wit and personality.

you do the hard job of making computer geek-stuff
fun and engaging to learn more.

hope you are doing well and wishing you
a warm and cozy winter if you are in montreal.

stay gold-
vincent, in buffalo

not sure why but the quiz is

not sure why but the quiz is not giving score.

I updated my web site to Drupal 5

Look in your Firebug console. isJsEnabled is not defined in exam.js. I will fix that. Javascript is not handled the same way in Drupal 4.7 and 5. Thanks for bringing this to my attention.

It is now fixed.

All functions defined in drupal.js are namespaced in Drupal 5, to avoid conflict with other Javascript libraries, which is quite an improvement. So I had to replace this line of code: if (JsEnabled())... with this one: if (Drupal.JsEnabled). Drupal.JsEnabled is a boolean property.

I also had to use jQuery's $(document).ready() function instead of addLoadEvent(). addLoadEvent() no longer exists in Drupal 5.

Nice post, thanks. Wanted to

Nice post, thanks. Wanted to tip but afraid it's not possible. Why don't they use paypal, anyway?

Of course it is!

See the donate link in the top top menu? That uses Paypal.

The direct link.

Your name will appear here.

Yeah... that's what I thought

You cheap fly by night leeching bastard are not coming back. That was just some cruel carrot-hanging over my face. By the way, it is possible to donate using Paypal with Tipjoy. You do have to provide an email address though. I have had that one played on me before... Thanks for nothing, you, dignified representative of why this world is going to hell.

Why the animosity? Because I have been burnt, burnt, burnt. And then burnt again, and again. All my orifices are way too sore.

By the way, I approve accounts at least on a daily basis. Yet some people write to me emails, saying : I would have donated to you if you had approved my account (within a few hours of requesting an account). And of course, when their account is activated, they go and download stuff, and do not donate anything at all. So predictable.

Nicely explained

There are number of cases where I just ended up copying php code rather than working my own php true or false code. This is helpful - bookmarks. Tom, 7AutoInsQuotes

Interesting article. Not

Interesting article. Not knowledgeable enough (yet) to add comment on it.

Would like to express my surprise at the animosity towards people that [i]say[/i] they will donate. Surely they are no worse than people like me who say nothing about it, yet still read the article? In fact, I'd go as far as to say that I would rather here people say they would donate, even if they don't. Perhaps their intentions were good. Perhaps they forgot.

Anyway, your post has perhaps lost you a new reader. Sorry.

No problem

In fact, I'd go as far as to say that I would rather here people say they would donate, even if they don't.

Not me. I only have a beef with people who talk about donation, but never follow through. I have no problem with people who do not donate. This website is free. You do not need to pay to read, and you do not need to pay to download anything.

Anyway, your post has perhaps lost you a new reader. Sorry.

No problem. You make it sound like I've lost a customer. I am not running a store here. I have a sharp tongue, and it gets me in trouble sometimes, but overall it serves me well. If I were to not express myself on certain subjects that deeply irritate me I would get sick — and sicker.

PLEASE NOTE: the strpos

PLEASE NOTE: the strpos function in the last example has the order of the arguments mixed up!

SHOULD BE: strpos($haystack, $needle)

Blasted PHP and it's inconsistency. Please fix so as not to further this cycle of misunderstanding!

Thank you!

I corrected the code snippet just now.

Informative Post

Really informative and cool post.
thanx for the post.

Finally!

I've finally understood why strpos must be used with !==

tnx!!!

Good post

Your post was informative and concise. You cleared up some questions I had about the interpreter behavior. Thanks for putting this up. And don't worry about people who criticize you or pretend they want to donate. They're just acting like jerks.

I learned something today.

I learned something today.

EASIEST WAY TO REMEMBER IT FOR LIFE! -- NAME SPACE

This is great for the newbie to learn from. Always good to get into it a bit and make all kinds of examples. I want to add that this is not just a PHP thing. I have been programming for 25 years. This is pretty much every language. The concept of isset only started in php.

If you really want to learn it you need to come back and simplify it. The way to cut to the chase with it is with the concept of name space. "Name space" is the actual place in memory where which the name of the variable and the value of such variable is stored. This section of memory is called the name space.

(1) DID YOU CREATE A NAME SPACE OR NOT?
Remember declaring/setting, empty or not, a variable creates name space.
--------------------------------------------------------

  • No name space created = false or null
  • Name space created = some value

(2) WHAT IS THE VALUE OF THAT NAME SPACE?
---------------------------------------------------------

  • False = 0 (zero) ..or.. nothing ( '' ) ..or.. again, no name space
  • True = 1 (one) ..or.. any value

So when checking for true or false it really is that simple.

Now as for isset?

Remember that isset is only checking "Is their name space". SO yes, doing an isset on a declared variable will come back as true because that is all the isset does. It does not check for value, it checks for declaration. (isset = Has this variable been set/declared. hehe or is-it-set? Not is-it-valued! Set means does it exist? )

So THANKS to php you now have to ask yourself 1 of 2 things. Is what I am doing checking for the existence of a variable in the name space memory.... or is what I am doing, checking for the value of that variable in the name space.

In short.. one more time....

isset checks if the variable is there or not, where as true or false is either an answer to a variable value, or of an instance of a variable name in memory. DONE, you remember this, you remember it for life. This is your key map, those 2 questions. Which one is the answer! Done!

What is even cooler is when you learn to place php code, part of your program, inside a variable and then be executed. As opposed to the usual script of code starting from top to bottom of your php page. When you learn to place code to be executed into variables to be executed is when you start learning what is called object oriented programming. That one took me a while to understand. Code inside a variable is your object. Having multiple variables with that same set of code in them are called your instances of an object. But, one must get the basics of true false, instance in memory or not, which is what this web page article does a great job of teaching. So Kudos to the writer!

Still reading through your site.

I keep finding more and more useful things though, I am hooked. Why did you quit posting in December though?

Finally.

True of false in php, that was the answer I was looking for, great! I had been looking for the solution for over one hour now... suchmaschinenoptimierung

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <css> <html> <javascript> <mysql> <php> <span> <a> <b> <i> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <sup> <sub> <dd> <del> <blockquote> <img> <q> <p> <div>
  • Lines and paragraphs break automatically.
  • You can enable syntax highlighting of source code with the following tags: <css>, <html>, <javascript>, <mysql>, <php>, <rails>, <ruby>.

More information about formatting options

CAPTCHA
I have to wonder if you're a human spammer or a machine, or less likely someone who cares to leave his or her thoughts behind.