namdh
namdh

Reputation: 73

Division operator in PHP

I accidentally do a division operator in PHP like this:

$a = 012; //or 0012 or even 00012
echo $a/4;
echo gettype($a/4);

I got output is: 2.5 double. //I don't know why output is 2.5.

I tried again:

$a=12;
echo $a/4;
echo gettype($a/4);

This will output 3 Integer.

I have read documentation in https://secure.php.net/manual/en/language.operators.arithmetic.php but still cannot understand this.

Can anyone help me please?

Upvotes: 0

Views: 764

Answers (2)

Carl Casbolt
Carl Casbolt

Reputation: 112

One thing that you can do is to clean the value of $a before you use it.

$a = ltrim($a, '0');

This will remove all preceding 0s and mean that 012 => 12 and not 10 when you cast it to an int

e.g.

$a = 0012;
$a = ltrim($a, '0');
echo $a/4;
echo gettype($a/4);

Upvotes: 0

John Conde
John Conde

Reputation: 219814

A value that stars with zero is octal. So 012 in octal is 10 in decimal. 10 divided 4 is 2.5.

Upvotes: 9

Related Questions