user
How to convert a string into integer in PHP?
alphonsio

In PHP, the function intval() get the integer value of a variable:

echo intval(39);	// 39
echo intval(3.9);  	// 3
echo intval('28'); 	// 28
echo intval('t'); 	// 0
echo intval('28t');	// 28

In PHP, you can convert a string into an integer using several methods. Here are the most common ways:

1. Using (int) or (integer) Cast

You can cast the string directly to an integer using (int) or (integer).

$string = "123";
$integer = (int) $string;

echo $integer; // Outputs: 123

2. Using intval() Function

The intval() function is used to convert a variable to an integer.

$string = "123";
$integer = intval($string);

echo $integer; // Outputs: 123

3. Using settype() Function

You can use the settype() function to change the type of a variable.

$string = "123";
settype($string, "integer");

echo $string; // Outputs: 123

Important Considerations:

  • If the string contains non-numeric characters, PHP will only convert the initial numeric portion of the string.

    $string = "123abc";
    $integer = (int) $string;
    echo $integer; // Outputs: 123
    
  • If the string doesn't start with a number, it will convert to 0.

    $string = "abc123";
    $integer = (int) $string;
    echo $integer; // Outputs: 0
    

These methods effectively convert a string to an integer in PHP depending on your needs.