True/False Question

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
BigAbe
Forum Commoner
Posts: 66
Joined: Fri Mar 31, 2006 7:41 pm

True/False Question

Post by BigAbe »

Ok... We're having a small office debate about this, so I thought I would throw this at you guys.

Code: Select all

$var = true;

echo $var;
Gives us 1

BUT

Code: Select all

$var = false;

echo $var;
Gives us "" (no printout)

Why is this and can this be changed?

-- Abe --
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Post by Christopher »

I think you are seeing a behavior of echo rather than the internal representation of the data. It's probably just how Rasmus first implemented it (maybe because of how Perl interpreted the vars) and it has stayed that way. To really check the vars try:

Code: Select all

$var=true;
var_dump($var);
$var=false;
var_dump($var);
(#10850)
User avatar
Ambush Commander
DevNet Master
Posts: 3698
Joined: Mon Oct 25, 2004 9:29 pm
Location: New Jersey, US

Post by Ambush Commander »

You could also...

Code: Select all

echo (int) $var;
Which would print 0 for false.
BigAbe
Forum Commoner
Posts: 66
Joined: Fri Mar 31, 2006 7:41 pm

Post by BigAbe »

I'm just confused as to why echoing a false variable doesn't result in a "0" versus an empty printout.

-- Abe --
User avatar
Ambush Commander
DevNet Master
Posts: 3698
Joined: Mon Oct 25, 2004 9:29 pm
Location: New Jersey, US

Post by Ambush Commander »

You're casting a boolean object to a string. The behavior is documented here: http://us2.php.net/manual/en/language.t ... ng.casting claiming that setting it empty will make it possible to cast back to boolean (although a string = '0' also casts to zero).

It's one of life's little mysteries. I'd believe arborint.
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post by RobertGonzalez »

I think that passing checkboxes follows along the same lines. When a checkbox array var is passed that is checked, it passes as 'On', but when it is not checked it passes as ''. I always wondered this, but never enough to bring it up. Thanks for starting the thread.
User avatar
Ambush Commander
DevNet Master
Posts: 3698
Joined: Mon Oct 25, 2004 9:29 pm
Location: New Jersey, US

Post by Ambush Commander »

Actually, for checkboxes, it's just not set at all. ;-)
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post by RobertGonzalez »

Sorry, I wrote that wrong. You are right AC. They are not set at all.
Post Reply