Hi...
I have a small doubt about php print statment. pls let me know if there is any reason
Here is a doubt for me.

<?php
$a=08;
print $a;
?>

why its output is 0.

Recommended Answers

All 5 Replies

Hey.

Because when you add a 0 to the start of an integer, PHP assumes you are using octal notation, in which the number 8 does not exist.

To print 8 in that way, you would have to do:

$a=010;
print $a;

See the manual for details.

I would try

$a = 08;
print($a);

or use a string

$a = '08';
print($a);

Neither of those actually change anything, samarudge.

Your first example is exactly like the one the jeet_portal posted in the first post. Using print instead of echo makes absolutely no difference in this context.
Because you do $a=08; , the value of $a will always be 0. You start of with a 0, which makes PHP read it as an octal integer. And because you use 8 - which doesn't exist when using octal notation - it is truncated, leaving only the 0.

The second one will be printed as is. It's a string, and PHP has no reason to convert it before printing it. Not unless you give it a reason to, which you don't.

You could fix this, though, by having sprintf convert a string version of the number into a proper decimal number.

<?php
$a = (int)sprintf('%d', '08');
echo $a;
?>

Neither of those actually change anything, samarudge.

Your first example is exactly like the one the jeet_portal posted in the first post. Using print instead of echo makes absolutely no difference in this context.
Because you do $a=08; , the value of $a will always be 0. You start of with a 0, which makes PHP read it as an octal integer. And because you use 8 - which doesn't exist when using octal notation - it is truncated, leaving only the 0.

The second one will be printed as is. It's a string, and PHP has no reason to convert it before printing it. Not unless you give it a reason to, which you don't.

You could fix this, though, by having sprintf convert a string version of the number into a proper decimal number.

<?php
$a = (int)sprintf('%d', '08');
echo $a;
?>

Great info Atli... Guess i need to get back to basics.. never knew this stuff!!
really appreciate it..
keep rockin...

Thanks Atli.....Enjoy....

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.