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 5 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

Programming language such as

Programming language such as this are not easy to understand, I had to open the reference and some books to learn the codes must be entered when applying this program. Therefore, I usually entrust it to someone more expert in this field.

Thanks.

That's what I like abou this blog. You explain difficult things in an easy to understand way. Thanks a lot for this. telefonkonferenz

PHP

People wrongly always believe that php is easy to master, which it is not. While it is a very logical language, it is quite hard to write good code in php. sonderfahrten

A statement should be thrown

A statement should be thrown well certainly. You will see Lots of people who given assertions that aren't considerate and also started to be a problem. check it out

A logic of a programming

A logic of a programming language that can never be denied is the use of true and false. These are two things that really can not be separated from one another. Dallas IT Support

puppy comforter

Right and wrong in applying the PHP does not make me worry too. This is because I have entrusted it to develop a blog to someone more experienced.

A truth and one's are two

A truth and one's are two different things and can not be made ​​into one and the same. In also applies to those who make a program with logic in a programming language. Fishing Lodges Alaska

I have learned a lot about

I have learned a lot about PHP applications like this. Several times I've tried to apply the necessary code, but I always found the error. I am confused about whether there is something wrong with the way the do?

here are a lot of logic that

here are a lot of logic that you should think about when you create a program properly. You really should use a programming language is good and suitable. juicing benefits

This indeed is one of the

This indeed is one of the logic that there will never be dead in a programming language. You really should choose who can and correct logic in many applications. drainage solutions

This is a case that is

This is a case that is widely used by many people who make a program or application. You do have to use a lot of ways that can be used to create the program 服飾批發

A logic of right and wrong

A logic of right and wrong it is a totally different thing. Both of these can not be taken the middle road because it's two very different things in the world. glock parts

We were able to use a lot of

We were able to use a lot of this statement when we're making an existing programming language. A logic programming language is a strong need. ghillie suit

I have not used this

I have not used this application before. In my opinion, this application is an application that is quite new and has a wide range of advantages compared to other applications.

There are a lot of logic

There are a lot of logic that must be considered by a programmer. However, a logic that will never be forgotten is the mechanism of right and wrong. This is the basic programming. chinup bar

Web Design Anchorage

Choice is always exists in this life. We are almost need to choose many important things in this life and sometimes those choices are not great at all for us.
Web Design Anchorage

web development

Hi! This is my first visit to your blog! And your blog provided me with valuable information to work on. You have done an extraordinary post! Forward more people to visit your site.
web development uk

This indeed is one of the

This indeed is one of the logic that is not negotiable. There are many people who do know that it's already become one of the logical decision is final. http://www.breezeoutdoorsettings.com.au/

true in php

I did not knew much about the subject but I got really hooked into it right just before started reading. cool! this web

no one here

There are lots of things a programmer needs to cope with, this is just one of them,. Thanks for your knowledge. get more

Have not seen this

Hey guys I have never seen something like this before, its amazing what can you do just with coded letters and numbers. Great work.

The post is written in very

The post is written in very good manner and it contains many useful information for me. you have a very impressive writing style .I really enjoyed what you had to say.Well, at least i am interested. focus group

Keep up the good work.

Twin Fountains EC facilities provide full family entertainment needs for your family and loved ones. Indulge in a serene and tranquil lifestyle right in the heart of Woodlands.
Woodlands EC

Good thoughts and well-written

Bartley Ridge will be accessible via Bartley MRT station on the Circle Line. Commuting to Toa Payoh and Paya Lebar area as well as the city area is therefore very convenient. It is also near to many eateries along the Upper Serangoon area as well as NEX shopping mall.
Bartley Condo

Informative thoughts

Belgravia Villas is also near elite schools such as Chatsworth International School and Lycee Francais De Singapour. Nanyang Polytechnic and Anderson Secondary School are also around in the area.
For vehicle owners, it takes less than 20 minutes to drive to the business hub and vibrant Orchard Road shopping district, via Central Expressway (CTE).
A wonderful and unique lifestyle awaits you. Please see Belgravia Villas project details and floor plans for more information.
Ang Mo Kio Cluster House

Article on "True or false in

Article on "True or false in PHP" is great resource for buddy web designers. Thanks!

Thank you again for all the

Thank you again for all the knowledge you distribute,Good post. I was very interested in the article, it's quite inspiring I should admit. I like visiting you site since I always come across interesting articles like this one.Great Job. HP officejet pro L7780 manual

The site looks a little

The site looks a little flashy, it caught the eyes of tourists. The design is very simple and user-friendly interface permanent magnet alternator

Several buses are available

Several buses are available near Ecopolitan EC along with shopping centers and restaurants. Ecopolitan EC is also near Waterway Point, the shopping, dining and entertainment hub which is scheduled to open in 2 years time. Also, it is right beside Punggol Waterfront. Entertainment for your loved ones and friends are therefore at your fingertips with the full condo facilities as well as the amenities near Ecopolitan EC.
Ecopolitan EC

thanks for post True or

thanks for post True or false in php

Jewel at Buangkok is also

Jewel at Buangkok is also near elite schools such as Nan Chiau Primary School and Nan Chiau High School. Montfort Junior School Holy Innocents' High School and Chij Our Lady Of The Nativity are also around in the area.
Buangkok New Launch

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 Jurong East.
J Gateway

Coral Edge Residences will

Coral Edge Residences will be accessible with Punggol MRT Station as well as Punggol Bus Interchange. It is also right beside Tampines Expressway(TPE). Coral Edge Residences is also near to Marina Country Club, Sengkang Riverside Park and Sheng Siong hypermart in Punggol Central.
Thx
Coral Edge Residence

DUO Residences will be

DUO Residences will be accessible via Bugis MRT station on the Circle Line. Commuting to Toa Payoh and Paya Lebar area as well as the city area is therefore very
convenient. It is also near to many eateries along the Bugis Heritage Area as well as the Bras Basah Area.
DUO Residence

fygrfyergrgreb

fygrfyergrgreb

Several buses are available

Several buses are available near Forestville EC along with shopping centers and restaurants. Forestville EC is also near Causeway Point as well as Woodlands Waterfront. Entertainment for your loved ones and friends are therefore at your fingertips with the full condo facilities as well as the amenities near Forestville EC.
Forestville EC will be accessible with Woodlands MRT station & Admiralty MRT station. It is also near to Vista Point Shopping Mall, Causeway Point Shopping Mall, Cold Storage, Shop N Save, and many more.
Forestville EC

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 Bartley.
Several buses are available near Bartley Road and Upper Paya Lebar Road along with shopping centers and restaurants.
Former Tai Keng Court

It's an iconic post. I have

It's an iconic post. I have learned a lot of knowledge from this post. I will bookmark your site for my future reference. Thanks for sharing this post.
Waterfront Condominium
dpristine video

Several buses are available

Several buses are available near Skypark Residences along with shopping centers and restaurants. Skypark Residences is also near Sembawang Shopping Centre as well as Woodlands Waterfront. Entertainment for your loved ones and friends are therefore at your fingertips with the full condo facilities as well as the amenities near Skypark Residences.
SkyPark Residences

Managing Properties in Languedoc Roussillon

Topics also very clear, very friendly, can let the reader with the attitude of the care to read such a good article.
Managing Properties in Languedoc Roussillon

CalHealth

Future residents will be able to access the nearby Compass Point and Greenwich V which is a short drive away for some family fun and gatherings. A truly unique lifestyle awaits you.

Commuting to Tampines as

Commuting to Tampines as well as the city area is therefore very convenient. The Glades is also near to Changi Airport as well as Changi International Business Park.
The Glades is also near elite schools such as Anglican High School, St. Anthony’s Canossian Primary & Secondary School and Temasek Junior College. Tampines Junior College, Temasek Polytechnic and United World College (East Campus) is also around in the area.
The Glades Tanah Merah

You have made an interesting

You have made an interesting blog. It contains a lot of valuable knowledge. I will bookmark this page for my future reference. Thanks!
TP180 Guocoland
http://www.youtube.com/watch?v=Lu4IUfW2qK4

waterwoods ec

Waterwoods EC is a new upcoming executive condominium at Punggol Field Walk. It is within close proximity to Coral Edge LRT. There are a total of 373 units developed by no other than renowned Sing Holdings. It is a 99 year lease hold property that is near to renowned school Mee Toh School. Waterwoods EC

look here

Interesting post and thanks for sharing. Some things in here I have not thought about before. Thanks for making such a cool.
look here

medicalassistingcareer101.com

It was really nice to study your post. I collect some good points here. I would like to be appreciative you with the hard work you have made in skill this is great article. .medicalassistingcareer101.com

Future residents are within

Future residents are within walking distance to Bishan Junction 8 and a short drive to Ang Mo Kio Hub from Sky Vue Condo. With such a short drive to the city area as well as the orchard and bugis area, entertainment for your love ones and family will come at a stone’s throw away from Sky Vue Condo Bishan Sky Vue

Year 2012 has been quite

Year 2012 has been quite eventful. SRSG also witnessed events and evolved in terms of business verticals, technologies, people and processes.

SRSG incorporated in 1997

SRSG incorporated in 1997 with a vision to provide the technology of Apple. SRSG is one and half decade old agile and adaptable company dealing with wide spectrum of broadcast IT and media technology products and services.

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.