I recently got a bit surprised when I saw this casting result.
echo (float)12,3;
echo "\n";
echo (float)"12,3";
The first will give us 123
and the second 12
.
What is the difference?
Simple
echo (float)12,3;
Means you are sending two values to echo as a comma separated list of parameters. 12
and 3
, which echoed together look like 123
. You can echo hundreds of things together in 1 call, PHP doesn't mind.
echo (float)"12,3";
You are sending a string "12,3"
to echo after casting it to a float
. When its converted to float it becomes 12 which you see being printed.
The difference is that PHP is seeing 12,3
as 12
and 3
. PHP simply removes the non-numeric character.
var_dump(12,3);
int(12)
int(3)
"12,3"
is a string and PHP is throwing out everything after the first non-numeric character.
echo (int)"12b3"; // also outputs 12
In php, ,
is also a concatenation operator, so 12,3
is interpreted as 123
.
But,
"12,3"
is a string and ,
is treated as character, so converting string to float resulting in 12
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With