How to convert a PHP string to an integer?

One way to convert a string into an integer in PHP is by using the built-in function intval(). The intval() function can change a string into an integer and allows specifying the base, such as decimal, octal, or hexadecimal.

Here is an example code:

$str = "12345";
$int = intval($str);

echo $int; // 输出:12345

When converting a string containing non-numeric characters to an integer, the intval() function will automatically ignore the non-numeric characters and only return the numeric part. For example:

$str = "12abc34";
$int = intval($str);

echo $int; // 输出:12

Please note that when converting a string to an integer, the intval() function automatically handles any spaces, symbols, or other characters within the string, only returning the valid numerical portion.

Leave a Reply 0

Your email address will not be published. Required fields are marked *