Search code snippets, questions, articles...

Convert String to an Integer in PHP

We can use the int keyword to convert a String value to an integer type value in PHP. Check the code examples explained in this post.
<?php
  // Define a string
	$my_str = "30";
	
	// Convert to integer value
	$val = (int)$my_str;
	
	echo $val;
?>
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place. Check how cool is the tool

Output

30

We are using (int) here to convert a String to an integer value using PHP. Some more examples to convert a String to numeric data types using PHP are as below.

Convert a String to float

<?php
   $my_str = "30.8";
  
   $val = (float)$my_str;
   echo $val;
?>

Output

30.8

Convert a string to double in PHP

<?php
  $val = (double) "50.8";
  echo $val;
?>

Output

50.8

Use intval() function to convert String to Int

We can also use the intval() function of PHP to convert a String to an integer type value.

<?php
    $val = intval("50");
    echo $val;
?>

Output

50

Convert String to float using floatval() function

<?php
    $val = floatval("50.3");
    echo $val;
?>

Output

50.3
Was this helpful?
0 Comments