How to Convert String into Integer in PHP?

A string value can be converted into an integer value through type casting or intval() function in PHP. Let’s suppose we have a variable $cars that has a string value. Before going into detail let’s check its type.

$cars = "10";
echo gettype($cars);
// OutPut: string

To check the variable type you can use gettype() function that accepts an argument and returns the type of variable accordingly.

Convert String Through intval() Function

In PHP, we can use the intval() function for converting string value into integer. It accepts parameters in which the first is required and the second is optional. Let’s use intval() function to convert $cars variable’s value into an integer. To do that, simply pass $cars variable into intval() function. Here we can assign the intval() function result to any new variable to use it further. Below is an example

// convert string into integer
$convertIntoInteger = intval($cars);
echo gettype($convertIntoInteger);
// OutPut: integers

Convert String Through Type Casting

To convert a string value into an integer through type casting you need to attach parenthesis with type along with the variable.

// convert string into integer
$convertIntoInteger = (int)$cars;
echo gettype($convertIntoInteger);
// OutPut: integer

Above we converted string value into integer and assigned it to variable $convertIntoInteger. Let’s check the full detail of variable $convertIntoInteger using var_dump() function.

var_dump($convertIntoInteger);
// Output: int(10)


Related Posts

Tags: Integer, PHP, String,