PHP and leading zeroes mindtrick

cenobite321

Member
Messages
77
Reaction score
0
Points
6
Hello everyone,

I've just got an e-mail from a friend telling me how PHP disliked leading zeroes. He attached the following code:

PHP:
 <?php
 for($i=01;$i<=07;$i++){
 print $i;
 echo "<br>";
 }
 
 for($i=01;$i<=08;$i++){//with 8 or more it fails
 print $i;
 echo "<br>";
 }
 ?>

As the comment highlights the second for statement fails and numbers are not displayed like in the first one. I made the following analysis of both numbers:

PHP:
 $foo = 07;
 //print the type of 07
 print '07 is a: '.gettype($foo).'<br>';
 //print the value of 07
 print $foo.'<br>';
 //adds 07 plus 1 and prints the result
 $foo = $foo +1;
 print $foo.'<br>';
 
 
 $foo = 08;
 //print the type of 08
 print '08 is a: '.gettype($foo).'<br>';
 //print the value of 08
 print $foo.'<br>';
 //adds 08 plus 1 and prints the result
 $foo = $foo +1;
 print $foo.'<br>';

The outcome was this:
07 is a: integer
7
8
08 is a: integer
0
1

Weird...:nuts:
 
Last edited:

marshian

New Member
Messages
526
Reaction score
9
Points
0
PHP doesn't dislike leading zeroes, leading zeroes mean something =P

I have a test for you, try the following script before you read on:
PHP:
<?php
header("Content-type: text/plain");

$one = 001;
$eight = 010;
echo $one * $eight;
?>
Do you know now?

-----------------------
A leading zero means the number is octal. The octal numeric system consists of 8 different numbers (0-7), it's related to the hexadecimal system, which uses 16 (0-F).
If you write 01, this means 1⁽⁸⁾ (read: 1 the numeric system with 8 symbols). This also equals 1⁽¹⁰⁾ in the more common decimal system.
Writing 010 however means 10⁽⁸⁾ which is the same as 8⁽¹⁰⁾.
Thus, using 8 or 9 in a number with leading zero indicates an invalid number (since 8 and 9 don't exist in the octal system). Therefore, the variable is assigned the default value of 0.
That pretty much explains this phenomenon, any questions?
 

descalzo

Grim Squeaker
Community Support
Messages
9,373
Reaction score
326
Points
83
Weird...:nuts:

Not really.

In most programming languages

x = 011

gives x the value of 9.

while

y = 0x11

gives y the value of 17

Leading 0x signifies hexidecimal, or base 16. You use 0-9 and a-f (or A-F) as numerals.
Leading 0 with no x signifies octal, or base 8. You use 0-7 as numerals.

Since 8 is not a legal octal numeral, 08 either causes an error, or is evaluated as zero ( 0118 would be evaluated as 011 or decimal 9).
 
Top