Skip to content
Advertisement

Integer value returns 0 after trying to convert it from string

I have variable like this with the type of string:

$price = "65000"

Now I tried setting it’s type to integer, so I tried these:

$finalprice = (int)$price; // returns 0
$finalprice = (intval)$price; // returns 0

So how to properly return the value 65000 as integer?

Advertisement

Answer

You wrong code, the first it’s correct and the second is intval($variable)

$price = "65000";

$finalprice1 = (int) $price; 
$finalprice2 = intval($price);
var_dump($finalprice1);
var_dump($finalprice2);

/*
int(65000)
int(65000)
*/

I hope it’s just a typing error but in the variable you didn’t close with ;


Another method you can use is settype like:

$price = "65000";
settype($price,'int');
var_dump($price);

/*
int(65000)
*/

Reference:

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement