note 29346 modified in function.is-int by philip

From: Date: Thu, 29 May 2003 20:48:05 +0000
Subject: note 29346 modified in function.is-int by philip
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-49294@lists.php.net to get a copy of this message
[[Editors note: Or you can simply use is_numeric()]] Some people have offered their ways to find out if a string from a form is an integer or not, here's my way: if(ereg("^[0-9]+$", $_POST["number"])) $_POST["number"] = (int)$_POST["number"]; In psuedo code: if you are a string full of numbers then convert yourself to an integer So instead of just checking if its a string full of numbers you check and then convert it, which means you can use the standard is_int. You can also do: if(ereg("^[0-9]+$", $_POST["number"])) $_POST["number"] += 0; I think the first way i mentioned is better because your coding what you want to do, rather than the second way that uses a side effect of adding 0 to convert the string. The first way also may make your code ever so slightly faster (nothing noticeable) as php does not need to add 0 to the number after it converts it. Also note an integer is full numbers (1, 2, 3 etc) not decimal numbers (1.1, 2.4, 3.7 etc), to convert decimal numbers you could use something like: if(ereg("^[.0-9]+$", $_POST["number"])) $_POST["number"] = (float)$_POST["number"]; OR if(ereg("^[.0-9]+$", $_POST["number"])) $_POST["number"] += 0; But note that these would not work with is_int(), because they are not integers. --was-- Some people have offered their ways to find out if a string from a form is an integer or not, here's my way: if(ereg("^[0-9]+$", $_POST["number"])) $_POST["number"] = (int)$_POST["number"]; In psuedo code: if you are a string full of numbers then convert yourself to an integer So instead of just checking if its a string full of numbers you check and then convert it, which means you can use the standard is_int. You can also do: if(ereg("^[0-9]+$", $_POST["number"])) $_POST["number"] += 0; I think the first way i mentioned is better because your coding what you want to do, rather than the second way that uses a side effect of adding 0 to convert the string. The first way also may make your code ever so slightly faster (nothing noticeable) as php does not need to add 0 to the number after it converts it. Also note an integer is full numbers (1, 2, 3 etc) not decimal numbers (1.1, 2.4, 3.7 etc), to convert decimal numbers you could use something like: if(ereg("^[.0-9]+$", $_POST["number"])) $_POST["number"] = (float)$_POST["number"]; OR if(ereg("^[.0-9]+$", $_POST["number"])) $_POST["number"] += 0; But note that these would not work with is_int(), because they are not integers. http://www.php.net/manual/en/function.is-int.php

« previous php.notes (#49294) next »