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 13 years ago.

Comments

The information you convey

The information you convey through your article on the web presenting this useful, I hope you will continue to present a good thing like this. Success to you and its web!

thanks for the information

thanks for the information you have provided.

nice info, thanks

nice info, thanks

thanks for your sharing.. i

thanks for your sharing.. i hope you can give the better information to next time.

alternatif

thanks for your information, very useful !

Obat Penyakit Asma
Obat Penyakit Hepatitis

tradisional

Page One

For vehicle owners, it takes

For vehicle owners, it takes less than 25 minutes to drive to the business hub and vibrant Orchard Road shopping district via Ayer Rajah Expressway (AYE). newly launched condo

The condo’s facilities

The condo’s facilities provide full family entertainment needs for your family and loved ones. Indulge in a serene and tranquil lifestyle right in the heart of the city. new commercial property

Entertainment for your loved

Entertainment for your loved ones and friends is therefore at your fingertips with the full condo facilities as well as the amenities near The Santorini. Tampines Ave 10 Condo

Several buses are available

Several buses are available near The Interlace along with shopping centers and restaurants. The Interlace is also near Mount Faber Park, the shopping, dining and entertainment hub. The Interlace online