PHP Convert String to Int

In this PHP tutorial, you will learn how to convert a PHP string to int. Depending on what calculation you will be doing with a variable, it may be important that it is of the particular type of integer.

For example, suppose you were processing (from a submitted form) a vote which was from 1 to 10; you would ideally want this data stored in a numeric variable rather than as a string which the $_GET or $_POST array would provide it to you as.

Converting a string to int in PHP is quite easy using casting as we will see below.

Casting a string to an int in PHP

To cast in PHP, we put the name of the desired type (that we are casting to) in brackets before the actual variable itself.

So if we wanted to cast a string to an integer we would do it like so:

<?php
 
$string = "526";
$integer = (int) $string; // cast string to integer
 
var_dump($string); // tell us about the variable $string
echo "<br />";
var_dump($integer); // tell us about the variable $integer
 
?>

The result would be:

string(3) "526"
int(526)

As we can see, our variable $string is treated as a string which is 3 characters long. Our $integer variable on the other hand is stored and treated as an integer.

We could also check that our variable was an int by using the === operator which checks the variable type in addition to the value.

<?php
 
$string = "526";
$integer = (int) $string; // cast string to integer
 
if ($string === 526)
    echo 'Our variable $string is an integer';
 
if ($integer === 526)
    echo 'Our variable $integer is an integer';
 
?>

If we ran that code we would get:

Our variable $integer is an integer

This is exactly what we expected. Since we checked if our variables were equal to 526 (without quotes), the only way our if statement was to return true, is if our variable was numeric and not a string.

We hope this PHP tutorial was helpful.

Thank Tutorial Arena for This Tutorial.
Show your appreciation with a +1...