Click here to Skip to main content
15,889,863 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
SQL
<?php

function show(){
$num=rand(0,1);
if ($num===1){
return true;
}
else
return false;

}
echo (boolean)show();
?>


even though I cast it to boolean it only show 1 when true.
But I read a php book which tell it works. This let me confused.
Thank you for your help.
Posted

1 solution

If your purpose is merely to echo the result, why not simply return 'true' and 'false' as strings ?

If you must return the value (which is 0 or 1), then change your ECHO to the following:

ECHO ((boolean)show()==1)?'true':'false';

Programming is at is best when you keep it simple.
 
Share this answer
 
Comments
Killzone DeathMan 8-Jan-14 10:29am    
Yeah thats ok! :)
I think making an echo true will show "1" and echo false will show ""! Right? :P
W Balboos, GHB 8-Jan-14 11:36am    
The echo of 1 (or 0 for false) is his problem. False is 0 in all languages I happen to know of. Now, with .php, you do need to be a bit careful when testing for true/false. If you want to test for 0 or not 0, you can use '==', but if you really want to test for the boolean true and false, you need to use '===', which is php's test with typing. This handles comparisons to NULL, which may mess with your results.


He wishes the text output - so either his function can return a text string or he can trap the return value and ECHO whatever he wishes base upon true or false. I've don't know a language that uses a blank or empty string for false.
Killzone DeathMan 8-Jan-14 12:59pm    
You are right that is better "===" to use, but what I desagree is when you run the code "<?php echo true; ?>", the page shows "1", and when you run "<?php echo false; ?>" it shows "" and not "0"! You are right, that FALSE is for all languages "0", but the PHP dont shows "0", it shows an empty string... I have tested it right now :P
But you are right, you have post a good solution ;)
W Balboos, GHB 8-Jan-14 13:08pm    
When you're right you're right.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900