tags:

views:

69

answers:

3
echo 1/3;

I was expecting the above to output 0, but in fact PHP is smart enough to output 0.33333333333333

Since when does PHP start to behave like this?

+9  A: 

It has always behaved like this. See: http://php.net/manual/en/language.operators.arithmetic.php

The division operator ("/") returns a float value unless the two operands are integers (or strings that get converted to integers) and the numbers are evenly divisible, in which case an integer value will be returned.

Daniel Egeberg
Isn't `1` and `3` already an `integer`?
wamp
@wamp: yes, but 1 is not evenly divisible by 3.
Michael Borgwardt
+1  A: 

PHP isn't a strongly typed language. It does things like that all the time.

As far as I know, php was designed like this from the beginning.

Ikke
Seems I misunderstood PHP from the beginning then...
wamp
The most crazy thing is the autocast from strings to integer, if the string only consists of numbers...
faileN
A: 

I'd say this is the expected behaviour.

If you want an integer, force a cast:

echo (int)(1/3);
Pekka
Isn't `1` the same as `(int)1` ?
wamp
@wamp you're right. I'm not really awake yet :)
Pekka
PHP isn't a strongly typed language. So 1 could be '1', 1, 1.00, "1" etc....
Lizard