Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print false in php [closed]

I am trying to print the following statement:

print false . "\n" . true . "\n";
echo false . (bool)false . "\n" . true . "\n";
print "0" . "\n" . true . "\n";

The result that I am getting is just "1 1 0 1". The expected result is:

0
1
0
1
0
1

I am using PHP 5.4.3 MSVC9 x64 Can someone please explain why and how I can make it print the correct way?

like image 970
Randall Flagg Avatar asked Mar 05 '26 14:03

Randall Flagg


2 Answers

Your problem comes from your misconception of the + operator on strings in PHP. The string concatenation operator is . as PHP is loosely typed, it doesn't know if you want to concat or add the strings.

I'll break it down for you:

print false + "\n" + true + "\n";
echo false+(bool)false + "\n" + true + "\n";
print "0" + "\n" + true + "\n";

First off you might want to pick to stay with echo or print. Now, onward:

print false + "\n" + true + "\n";

PHP strings, when added (not contacted), evaluate to 0. So this statement evaluates to:

print 0 + 0 + 1 + 0;

which is 1. The other ones follow suit. If you want your code to work, you should use the concatenation operator (.). If you want to write True or False like how .NET does, you could write a simple function:

function writeBool($var)
{
    echo ($var) ? "True" : "False";
}

As per PHP's loose typing (which sucks if you ask me), anything that will evaluate to true, will write "True". I would still discourage from using a function to do this as function calls in PHP are expensive.

like image 56
Cole Tobin Avatar answered Mar 07 '26 06:03

Cole Tobin


This should do the trick. Use an array.

$boolarray = Array(false => 'false', true => 'true');
echo $boolarray[false],"  ", $boolarray[true];

Output : false true

like image 30
Lion Avatar answered Mar 07 '26 06:03

Lion