Discussion:
key arrays should be integers when they are not what's happening exactly?
Negin Nickparsa
2014-07-21 00:22:33 UTC
Permalink
Hi

how PHP rounds the numbers in this case ?

$a = array(
0.5 => 1,
0.8 => 2,
1.2 => 3,
1.8 => 4,
);
print_r($a);
echo round(0.5);

we cannot have float keys so they will be rounded but I am wondering for
example rounding 0.5 will return 1 so from 0.1 to 0.4 all will be rounded
to 0
so it seems it is not doing the logic like the round function because the
$a output is :
Array ( [0] => 2 [1] => 4 )
what is the logic here?

Sincerely
Negin Nickparsa
David Harkness
2014-07-21 06:07:06 UTC
Permalink
Post by Negin Nickparsa
how PHP rounds the numbers in this case ?
It doesn't use the built-in round function but rather casts the floats to
int. You can achieve the same effect with the intval function and casting.
Post by Negin Nickparsa
echo intval(1.5);
1
Post by Negin Nickparsa
echo (int) 1.5;
1

Peace,
David
Negin Nickparsa
2014-07-21 22:25:18 UTC
Permalink
Thank you


Sincerely
Negin Nickparsa
Post by David Harkness
Post by Negin Nickparsa
how PHP rounds the numbers in this case ?
It doesn't use the built-in round function but rather casts the floats to
int. You can achieve the same effect with the intval function and casting.
Post by Negin Nickparsa
echo intval(1.5);
1
Post by Negin Nickparsa
echo (int) 1.5;
1
Peace,
David
Loading...