Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php string to int

Tags:

$a = '88'; $b = '88 8888';  echo (int)$a; echo (int)$b; 

as expected, both produce 88. Anyone know if there's a string to int function that will work for $b's value and produce 888888? I've googled around a bit with no luck.

Thanks

like image 540
agh Avatar asked Aug 10 '11 08:08

agh


People also ask

What does Intval mean in PHP?

Definition and Usage The intval() function returns the integer value of a variable.

How do you convert one variable type to another say a string to a number in PHP?

Method 1: Using number_format() Function. The number_format() function is used to convert string into a number. It returns the formatted number on success otherwise it gives E_WARNING on failure. echo number_format( $num , 2);

What is the use of int () in PHP?

The (int), (integer), or intval() function are often used to convert a value to an integer.


2 Answers

You can remove the spaces before casting to int:

(int)str_replace(' ', '', $b); 

Also, if you want to strip other commonly used digit delimiters (such as ,), you can give the function an array (beware though -- in some countries, like mine for example, the comma is used for fraction notation):

(int)str_replace(array(' ', ','), '', $b); 
like image 163
Gabi Purcaru Avatar answered Oct 29 '22 20:10

Gabi Purcaru


If you want to leave only numbers - use preg_replace like: (int)preg_replace("/[^\d]+/","",$b).

like image 23
XzKto Avatar answered Oct 29 '22 21:10

XzKto