php
Cast Comparisons and
Control Types
In studying for the php5 exam, I have found what is potentially the most trivial and stupid information in the php5 exam spectrum.
If you are going to take the php5 exam, you'd better bone up on this bit of super trivia. I call it "stupid" and "super trivia" because like when a good speller up against a word they probably can't spell right uses another word, a good programmer up against one of these stupid control-type trivia exercises would use a clear test that would not be misunderstood.
Nevertheless, please look through this piece of code. I'll paste its output below.
error_reporting(E_ALL);
echo "'t' == t:".(('t' == t) ? 'true' : 'false')."n";
echo '1 === "1t":'.((1 === "1time") ? 'true' : 'false')."n";
echo '"top" === 0:'.(("top" === 0) ? 'true' : 'false')."n";
echo '"top" == 0:'.(("top" == 0) ? 'true' : 'false')."n";
echo '"top" == 1:'.(("top" == 0) ? 'true' : 'false')."n";
echo '0 == "1t":'.((1 == "1t" ) ? 'true' : 'false')."n";
echo '1 == "1t":'.((1 == "1t" ) ? 'true' : 'false')."n";
echo "n";
echo '(string)"top" == (bool)0:'.(((string)"top" == (bool)0) ? 'true' : 'false')."n";
echo '(bool)"top" == (string)0:'.(((bool)"top" == (string)0) ? 'true' : 'false')."n";
echo "n";
echo '(string)"top" == 0:'.(((string)"top" == 0) ? 'true' : 'false')."n";
echo '(bool)"top" == 1:'.(((bool)"top" == 1) ? 'true' : 'false')."n";
echo '(bool)"top" == 1:'.(((bool)"top" == 1) ? 'true' : 'false')."n";
echo '(string)"top" == 0:'.(((string)"top" == 0) ? 'true' : 'false')."n";
echo "n";
echo '"top" == (int)0:'.(("top" == (int)0) ? 'true' : 'false')."n";
echo '"top" == (int)1:'.(("top" == (int)1) ? 'true' : 'false')."n";
echo '"top" == (int)2:'.(("top" == (int)2) ? 'true' : 'false')."n";
echo "n";
echo '"top" == (bool)0:'.(("top" == (bool)0) ? 'true' : 'false')."n";
echo '"top" == (bool)1:'.(("top" == (bool)1) ? 'true' : 'false')."n";
echo '"top" == (bool)2:'.(("top" == (bool)2) ? 'true' : 'false')."n";
And the output:
Notice: Use of undefined constant t - assumed 't' in test.php on line 3
't' == t:true
1 === "1t":false
"top" === 0:false
"top" == 0:true
"top" == 1:true
0 == "1t":true
1 == "1t":true
(string)"top" == (bool)0:false
(bool)"top" == (string)0:false
(string)"top" == 0:true
(bool)"top" == 1:true
(bool)"top" == 1:true
(string)"top" == 0:true
"top" == (int)0:true
"top" == (int)1:false
"top" == (int)2:false
"top" == (bool)0:false
"top" == (bool)1:true
"top" == (bool)2:true
- So firstly we realize that
evaluates to true thanks to the E_NOTICE that shows us that an undefined constant will be treated as a string.'t' == t
- The next one isn't so easy...why do both strings "top" evaluate to true when compared to 0 and 1? Because, as you see in the final six tests,
- zero cast to int evaluates to true and
- one (or any other none zero number) cast to bool evaluates to true
Last Updated: 2008-11-26 20:54:28