17. June 2007, 19:15, by Leo Büttiker

Crazy Numbers in PHP

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 100/"bags 10".

Meet hex…

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:

echo 0xFE;

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:

echo 0xFG;

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 (63) out.

… and octal numbers

So now we do some more stuff. Whats about this:

echo 088;

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).

Filed under: PHP,Programming


  1. Wow.
    This feature was probably already introduced in perl v1.0. ;)
    perl -e ‘print “10 a” * “10 b = 100″ . “\n”;’

    Comment by Ich — 17. June 2007 @ 21:58

  2. […] Leo wrote up something on tilllate techblog about numeric literals in PHP. […]

    Pingback by More PHP awesomeness : O RLY? — 19. June 2007 @ 22:43

RSS feed for comments on this post.

Sorry, the comment form is closed at this time.

© 2018 tilllate Schweiz AG - Powered by WordPress