Reputation: 41
I've been trying to convert string to int in PHP to operate on it, but PHP keeps interpreting it as 0.
var_dump ($Pux); // output: string (6) "89"
I have tried several ways like
(int) $Pux,
intval($Pux)
settype($Pux, "integer")
But they all give me 0 instead of 89.
How should this be done?
Upvotes: 2
Views: 16856
Reputation: 1
I had the same mistake. Indeed when i did var_dump($myvar). it returns string(2) "89" and when i did all the casts fonctions it returned me 0. I search and finally the answer is in this page. So I share with you what i learned. You have just to do a regex php : $myvar = preg_replace("/[^0-9,.]","",$myvar). It removes all the not number in your string (in my case the string(2)).
Upvotes: 0
Reputation: 1390
As var_dump($Pux);
outputs string(6) "89"
(not string(2)
), it means your string contains 6 symbol, I think they are 4 single brackets (')
and 89
. So try to remove brackets from your string:
$Pux = str_replace("'", '', $Pux);
or remove double brackets too (for safe)
$Pux = strtr($Pux, array("'" => '', '"' => ''));
EDITED
will be good to remove all non numeric values:
$Pux = preg_replace("/[^0-9,.]/", "", $Pux);
and then convert to integer.
Thanks.
Upvotes: 0
Reputation: 133
The code below removes the non numeric characters::
function numeric( $st_data )
{
$st_data = preg_replace("([[:punct:]]|[[:alpha:]]| )",'',$st_data);
return $st_data;
}
Upvotes: 0
Reputation: 1244
You can convert string to integer in two ways:
Typecasting or intval function
<?php
$pux = "89";
var_dump($pux);
$pux = (int) $pux;
var_dump($pux);
$pux = "89";
$pux = intval($pux);
var_dump($pux);
?>
Upvotes: 0
Reputation: 192
The easiest way to convert a string to a number:-
<?php
$Pux = "89"; // Or any other number
$Num = (int) $pux;
?>
If you are still getting a zero there might be some odd, invisible chars in front of the number. To test for that :-
echo "($Pux)";
Upvotes: 0
Reputation: 94682
There is not problem if you dont put spaces between $
and varname
and assign the result of the cast to a variable.
<?php
$Pux = "89";
var_dump ($Pux);
$t = (int)$Pux;
var_dump ($t);
?>
Output =
string(2) "89"
int(89)
Upvotes: 3