Uppercase Booleans vs. Lowercase in PHP
Asked Answered
L

11

150

When I was learning PHP, I read somewhere that you should always use the upper case versions of booleans, TRUE and FALSE, because the "normal" lowercase versions, true and false, weren't "safe" to use.

It's now been many years, and every PHP script I've written uses the uppercase version. Now, though, I am questioning that, as I have seen plenty of PHP written with the lowercase version (i.e. Zend Framework).

Is/Was there ever a reason to use the uppercase version, or is it perfectly OK to use the lowercase?

edit: Forgot to mention that this applies to NULL and null as well.

Latterll answered 6/1, 2010 at 15:11 Comment(6)
There is a number of sites saying that writing it lowercase is supposedly "much faster", but without citing any serious sources. Interested to see whether anything comes up.Crowley
That's not true. I tested it with 5M iterations and they both gave the same results, 0.5s on my PC :PMadea
@Madea Pekka may also mean that the actual writing of lowercase booleans is faster. That makes sense, having to use less keys. The difference is tiny, though.Castrate
Sorry, I accidentally voted down after after I voted up for you.Anderlecht
An interesting observation: var_export() writes true and false as lowercase, but NULL as uppercase. Lovely, eh? 3v4l.org/6OelkCoahuila
See #34468243Coahuila
T
99

The official PHP manual says:

To specify a bool literal, use the constants true or false. Both are case-insensitive.

So yeah, true === TRUE and false === FALSE.

Personally, however, I prefer TRUE over true and FALSE over false for readability reasons. It's the same reason for my preference on using OR over or or ||, and on using AND over and or &&.

The PSR-2 standard requires true, false and null to be in lower case.

Tombac answered 6/1, 2010 at 15:21 Comment(11)
Just want to point out that OR and || are different operators in PHP (as in they have different precedence), as are AND and &&. (So for example && and || are higher precedence than the assignment operators, but OR and AND are not.)Willner
Also with today's IDE's I do not see the reason to have pure upper-case boolean as the Syntax Highlighter for most IDE's separate them with great distinction.Murther
I much prefer typing them lowercase so I don't have to hold down the shift key.Bemis
I like lower case as well--like in java, but to each there own. I'd wish however they'd settle on ONE way and just make us all change over to one or the other!!!!! This isn't a flexibility I really need to have!Anagram
Another shame on PHP. True === TrUe === true === truE === TRUE === ... That's just nonsense...Vig
@Cyril: There are plenty of good reasons to indulge in hating PHP (e.g. just see what Johrn mentioned above, I didn't know that for one), but given that it's basically case-insensitive, there is nothing strange in mixed-case expressions being the same. What is nonsense, however, that it mixes case-sensitivity and case-insensitivity with general insensibility. (See e.g.: #5643996)Vixen
I believe it's more appropriate to say true === TRUE and false === FALSE (triple equal signs instead of 2), because true == 'false', true == 'true', false != 'false', false == '' all these conditions would return true.Obeded
The PHP Framework Interop Group have opted for true, false, null for PHP constants so as to match PHP keywords. github.com/php-fig/fig-standards/blob/master/accepted/…Buttonhole
"Readability" is not a good reason for choosing "AND" over "&&" and "OR" over "||" since they are not equivalent operands.Botryoidal
Anyone reading this, I would advise against using TRUE and FALSE in php since most of php programmers also use Javascript heavily, and in JS TRUE and FALSE are seen as constants and true and false are booleans. Just to make your life a bit easier.Kashakashden
I'd have upvoted your answer for the manual and PSR-2, but you have incorrect information about the OR over || .., please edit your answerSweatt
S
114
define('TRUE', false);
define('FALSE', true);

Happy debugging! (PHP < 5.1.3 (2 May 2006), see Demo)

Edit: Uppercase bools are constants and lowercases are values. You are interested in the value, not in the constant, which can easily change.


Eliminated run-time constant fetching for TRUE, FALSE and NULL

author      dmitry <dmitry>
            Wed, 15 Mar 2006 09:04:48 +0000 (09:04 +0000)
committer   dmitry <dmitry>
            Wed, 15 Mar 2006 09:04:48 +0000 (09:04 +0000)
commit      d51599dfcd3282049c7a91809bb83f665af23b69
tree        05b23b2f97cf59422ff71cc6a093e174dbdecbd3
parent      a623645b6fd66c14f401bb2c9e4a302d767800fd

Commits d51599dfcd3282049c7a91809bb83f665af23b69 (and 6f76b17079a709415195a7c27607cd52d039d7c3)

Safire answered 27/9, 2010 at 19:35 Comment(9)
-1 because A) this is pointless. B) this doesn't answer the question. and C) I've already accepted the correct answer, and this doesn't present any additional helpful information.Latterll
Then let me explain in detail: uppercase bools are constants and lowercases are values. You are interested in the value, not in the constant, which can easily change. So, if you would have thought a little on the text and not rush to give a penalty, you probably would have understood this.Safire
I understand the point you are making (now), but the way you originally made it was (IMO) cryptic and pointless. Had you originally just made your edit the answer, I would have upvoted, as this is a very good point, actually.Latterll
This is the right answer. Should have gotten the points for this.Rosewater
Actually, this is really in core code, fonnd by using Go To Definition on an all caps TRUE. in Code_d.php -- define ('true', true, true); define ('false', false, true); define ('null', null, true);Stirling
This is a compelling argument for always using lowercase versions. The Zend Engine will not allow the lowercase versions to be redefined, but any other spelling variation can be redefined: define('true', false); var_dump(true); /* "bool(true)" */, but: define('TRUE', false); var_dump(TRUE); /* "bool(false)" */, and even for NULL which is how var_export() describes it: define('NULL', false); var_dump(NULL); /* "bool(false)" */. I had always followed the var_export notation (true/false/NULL), but this is a good reason to switch to null instead.Coincidentally
As for the edit, that description is a bit misleading... The actual values themselves (which get compiled down into tokens T_NULL, T_TRUE, and T_FALSE at parse time), are case-insensitive, so using NULL is not actually a "constant" --- unless you make it a constant, using define(). Simply using NULL or TRUE does not mean it's a constant, as if there is no such constant, PHP interprets it as the literal. A more accurate description is that the lowercase versions cannot be redefined, whereas any other case variation can.Coincidentally
@Joe, It is a constant because PHP.net defines it as such: php.net/manual/en/… . And the lower case version can be redefined: namespace foo; define('foo\null', 'new value!'); var_dump(null);Hanshansard
It seems that since PHP 5.x, any define('FALSE', ..) is allowed but has no effect. 3v4l.org/nhkjL All the PHP versions where the issue would occur as described are now unsupported.Coahuila
T
99

The official PHP manual says:

To specify a bool literal, use the constants true or false. Both are case-insensitive.

So yeah, true === TRUE and false === FALSE.

Personally, however, I prefer TRUE over true and FALSE over false for readability reasons. It's the same reason for my preference on using OR over or or ||, and on using AND over and or &&.

The PSR-2 standard requires true, false and null to be in lower case.

Tombac answered 6/1, 2010 at 15:21 Comment(11)
Just want to point out that OR and || are different operators in PHP (as in they have different precedence), as are AND and &&. (So for example && and || are higher precedence than the assignment operators, but OR and AND are not.)Willner
Also with today's IDE's I do not see the reason to have pure upper-case boolean as the Syntax Highlighter for most IDE's separate them with great distinction.Murther
I much prefer typing them lowercase so I don't have to hold down the shift key.Bemis
I like lower case as well--like in java, but to each there own. I'd wish however they'd settle on ONE way and just make us all change over to one or the other!!!!! This isn't a flexibility I really need to have!Anagram
Another shame on PHP. True === TrUe === true === truE === TRUE === ... That's just nonsense...Vig
@Cyril: There are plenty of good reasons to indulge in hating PHP (e.g. just see what Johrn mentioned above, I didn't know that for one), but given that it's basically case-insensitive, there is nothing strange in mixed-case expressions being the same. What is nonsense, however, that it mixes case-sensitivity and case-insensitivity with general insensibility. (See e.g.: #5643996)Vixen
I believe it's more appropriate to say true === TRUE and false === FALSE (triple equal signs instead of 2), because true == 'false', true == 'true', false != 'false', false == '' all these conditions would return true.Obeded
The PHP Framework Interop Group have opted for true, false, null for PHP constants so as to match PHP keywords. github.com/php-fig/fig-standards/blob/master/accepted/…Buttonhole
"Readability" is not a good reason for choosing "AND" over "&&" and "OR" over "||" since they are not equivalent operands.Botryoidal
Anyone reading this, I would advise against using TRUE and FALSE in php since most of php programmers also use Javascript heavily, and in JS TRUE and FALSE are seen as constants and true and false are booleans. Just to make your life a bit easier.Kashakashden
I'd have upvoted your answer for the manual and PSR-2, but you have incorrect information about the OR over || .., please edit your answerSweatt
C
35

Use lowercase.

  1. It's easier to type. (IMO)
  2. It's easier to read. (IMO)
  3. JavaScript booleans are lowercase and case-sensitive.
Crankcase answered 10/6, 2010 at 17:0 Comment(1)
+1; I was just about adding the Javascript argument: as it's VERY common in web programming to write both PHP and JS code, well developed web development finger muscles continue to routinely apply the same letter case used in the last language context. At least I often found myself writing TRUE or FALSE in Javascript after switching from PHP. Using lower case in PHP fixed this one for good.Vixen
K
13

If you intend to use JSON, then RFC7159 says:

The literal names MUST be lowercase. No other literal names are allowed.

From the list of backward incompatible changes in PHP 5.6:

json_decode() now rejects non-lowercase variants of the JSON literals true, false and null at all times, as per the JSON specification

According to PSR-2 standard:

PHP keywords MUST be in lower case.

The PHP constants true, false, and null MUST be in lower case.

Kafiristan answered 26/1, 2015 at 15:50 Comment(3)
Correct, but this question was specifically in regards to upper/lowercase booleans in PHP, not JSON. For example, both json_encode(TRUE) and json_encode(true) yield 'true'.Latterll
Sorry for mentioning JSON, would it be better if I removed all those references and only mentioned PSR-2 ?Kafiristan
I think the reference to JSON is appropriate, as you frequently use javascript/JSON with PHP, and may be looking for consistency.Commandment
B
11

I used to do C style TRUE/FALSE booleans like all consts, in all caps, until I got on the PSR bandwagon.

Section 2.5 of PSR-2:

The PHP constants true, false, and null MUST be in lower case.

So basically, if you want to play nice with open source style particulars, Booleans gotta be lower case.

Botryoidal answered 3/7, 2015 at 1:11 Comment(0)
G
5

It doesn't matter, true is exactly the same as TRUE. Same goes for false and null. I haven't heard that it would have mattered at any point.

The only way you can mess things up is by quoting those values, for example:

$foo = false;   // FALSE
$bar = "false"; // TRUE

$foo2 = true;   // TRUE
$bar2 = "true"; // TRUE

$foo3 = null;   // NULL
$bar3 = "null"; // TRUE

Only thing restricting or encouraging you to use upper or lowercase might be your company's or your own coding guidelines. Other than that, you're free to use either one and it will not lead in any issues.

Gravettian answered 6/1, 2010 at 15:13 Comment(2)
FALSE and NULL are not the same. is_null() does not return true if the value === FALSE.Fehr
@Noah Goodrich, I did not at any point imply that false and null would be the same. I said that "same goes for false and null", which meant that both can be expressed in lower or uppercase letters.Gravettian
K
5

I've written simple code to check the differences between false and FALSE: Each iteration was doing something that:

    for ($i = 0; $i < self::ITERATIONS; ++$i) {
       (0 == FALSE) ;
    }

Here are the results:

Iterations: 100000000
using 'FALSE': 25.427761077881 sec
using 'false': 25.01614689827 sec

So we can see that performance is very slightly touched by the booleans case - lowercase is faster. But certainly you won't see.

Kevenkeverian answered 12/3, 2013 at 11:31 Comment(2)
What JS engine? Nowadays JS is compiled in memory before execution.Byword
PHP is tokenized before execution, and there should be no difference in time. Another answer indicated that upper was faster. Differences of this magnitude in any test should be ignored - this difference is 2.5e-7 per iteration.Commandment
O
4

Personally I've always used the lowercase form, but for no particular reason other than to make my code look tidy, the only place I use capital letters is when camel casing class names and variable names.

One advantage to using uppercase that comes to mind though is that they stick out and are easy to find in code.

Ordeal answered 6/1, 2010 at 15:21 Comment(1)
+1 for tidy-ness. All caps tradition comes from C, but it's about time we get rid of that ugly form.Loadstar
S
2

I came across this old question while asking myself the same thing. Good point with define('TRUE', false);define('FALSE', true); Doesn't apply to php5 though. Writing those lines in a php5 code is like writing a comment.

Spatula answered 17/1, 2012 at 5:43 Comment(2)
Just for future reference, you posted this as an "answer". On StackOverflow, unlike traditional forums, conversational posts that don't actually serve as a solution to the question and don't provide helpful information should be posted as a comment to either the original question or the relevant answer. In this case, your post would be better suited to a comment on my question than an answer.Latterll
actually it's helpful to know this doesn't work anymore in PHP 5 :PMadea
E
1

Here is my TEST on Windows 7x64bit Apache/2.4.9 PHP/5.5.14

$blockLimit = 50;
while($blockLimit > 0): $blockLimit--;

//STAR Here ================================================

$msc = microtime(true);
for ($i = 0; $i < 100000; $i++) {
   echo (FALSE);
}
echo 'FALSE took ' . number_format(microtime(true)-$msc,4) . " Seconds\r\n";
$msc = microtime(true);
for ($i = 0; $i < 100000; $i++) {
   echo (false);
}
echo 'false took ' . number_format(microtime(true)-$msc,4) . " Seconds\r\n";

echo "\r\n --- \r\n";
//Shutdown ==================================================
endwhile;

This time FALSE won 20 times. So uppercase is faster in my environment.

Elsewhere answered 13/7, 2014 at 23:55 Comment(0)
L
0

I am years late to the party but wanted to mention something interesting that isn't in the thread yet. Today I discovered True is also valid, not just true or TRUE. All spellings are equivalent. This is relevant because of the Open API generator for PHP, it uses True. (Which led me to a bewildered state of mind and a search which found this page).

Leisurely answered 28/9, 2020 at 14:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.