If you’re programming php for a while you know PHP has some fancy type converting stuff. Or do you know an other programing language that can do that?
echo “10 Apple” * “10 bags” //you get 100
The trick is simple, if you do a mathematical operation on a string, PHP tries to convert it in a number. It does the number parsing of the string from the left to the right, as long it’s a number and stop afterwards. So converting of “12 number 34″ will you just get you 12. If the string do not start with a number PHP converts it to a 0. So be careful about
Ok, until now this might be very obivous for some of you. But know it’s getting really crazy. As in a lot of other language you can define your numerical constants not only in decimal, you can do this also in octal or hex.
Ok, here we go:
Yeah, thats easy! (Or do you have to take the calculator?!) It’s just output the number in decimal and thats of course 254. But whats about that:
No, this time you calculator won’t help. Obivous this is not a hex number and you get a parse error (
unexpected T_String). So after this basics we try the same with octal, must be the same or not?
echo 077; is still simple. It’s just put the decimal value (
… and octal numbers
So now we do some more stuff. Whats about this:
Yeah, good trick! The number eigth is not in the octal system! I get a… No, you are wrong, I don’t get a parse error. I get a zero. Strange?! No, wait! It just gets weird: What happens if you put out
0786? No, you never guess (unless you wrote this part of PHP or the manual page by yourself)!
You get a seven! Its just the same which happens when you converting strings, PHP starts at the left and parse until the first wrong number and than it stops. Weird! But how cares! Or did you ever use octal numbers?
This is my first post on this blog. My Name is Leo Büttiker and I work for tilllate as a software architect for a bit more than a month now. I quizz the tilllate-team with silly (PHP) questions every day and even our Mister-I-know-all-3079-PHP-Functions Maarten might not know them all. If I find some time I’m also blog on my private blog (mostly in german).