Echo (float) 12.3; against echo (float) "12.3"; - Why the difference?

Recently, I was a little surprised to see 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?

+6
source share
3 answers

Plain

 echo (float)12,3; 

means that you send two values ​​for the echo as a list of parameters, separated by commas. 12 and 3 , which are repeated together, look like 123 . You can repeat hundreds of things in one call, PHP doesn't mind.

 echo (float)"12,3"; 

You send the string "12,3" for the echo after , sending it to the float . When it converts to float, it becomes 12, which you see printable.

+5
source

The difference is that PHP sees 12,3 as 12 and 3 . PHP just removes the non-numeric character.

 var_dump(12,3); int(12) int(3) 

"12,3" is a string, and PHP throws everything after the first non-numeric character.

 echo (int)"12b3"; // also outputs 12 
+2
source

In php , it is also a concatenation operator, so 12,3 interpreted as 123 .

But,

"12,3" is a string, and , treated as a character, so converting a string to float results in 12

+1
source

All Articles