PHP - parseInt

From Global Programming Syntax

Jump to: navigation, search

You may have heard of a function in the Javascript language called parseInt(). This function by default is not in the php language (to my knowledge) and can be recreated using the below script. So first place the script in the below code box near the top of your php file.

<?
function parseInt($val)
{
while (preg_replace('/([0-9])?[^0-9].*/is','$1',$val)!==$val)
{
$val=preg_replace('/([0-9])?[^0-9].*/is','$1',$val);
}
if ($val=='') { $val=0; }
return $val;
}
?>

Then to use it, do exactly what you do in Javascript except if between the brackets is a string, then you need to put quotes " " around that string (as shown below). Below are various ways of using it with a comment showing their output.

parseInt('a123b45');
//Outputs: 0
 
parseInt('56e44');
//Outputs: 56
 
parseInt('891+24');
//Outputs: 891
//Because of quotes
 
parseInt(891+24);
//Outputs: 915
//Because no quotes
 
parseInt(1283);
//Outputs: 1283

So it basically just chops off anything after (including) the first character that is not a number. And if the first character is not a number it returns 0.

Personal tools
languages
page stats
Toolbox