Cast string to either int or float Cast string to either int or float php php

Cast string to either int or float


No, no function provides the automatic cast. However you can cast with this simple hack (the cast is automatically made by PHP in internal):

$int = "123"+0;$float = "1.23"+0;

for generic number:

$yourNumberCasted = $yourStringNumber + 0;

With a function:

function castToNumber($genericStringNumber) {     return $genericStringNumber+0; }$yourNumberCasted = castToNumber($yourStringNumber);


There is no built in function to do that but you can create your own quickly.

function castNumber($n){   if(!is_numeric($n)) return 0;   return (is_float($n)) ? (float) $n : (int) $n;}

and use it:

$casted = castNumber($num_to_cast);


You can fulfil your requirement using following line.

 $i = "1.23";        echo $c = (double)$i; // will return 1.23 $i = "123";        echo $c = (double)$i; // will return 123