Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

echo (float)12,3; versus echo (float)"12,3"; - why the difference?

Tags:

php

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?

like image 935
konrad_firm Avatar asked Jan 19 '16 14:01

konrad_firm


3 Answers

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.

like image 180
Hanky Panky Avatar answered Nov 04 '22 05:11

Hanky Panky


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
like image 35
Machavity Avatar answered Nov 04 '22 05:11

Machavity


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

like image 25
Niranjan N Raju Avatar answered Nov 04 '22 06:11

Niranjan N Raju