This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Check if a variable is a natural number
Just came across where I need to sanitize an input and remove all non-digit characters with PHP. Thought of making a function myself, but just first wanted to check up on the possible built-in functions, so I won't have to spend extra time reinventing the wheel.
There isn't a direct equivalent to pareseInt() in PHP because PHP doesn't have a NaN data type. parseInt() will produce NaN if the value can't be parsed.
In addition, parseInt() has the radix parameter, which none of the PHP options give you.
But that said, if all you want to do is turn a string into an integer, then there are several options:
$int = (int)$string;
$int = intval($string);
$int = settype($string,'integer');
Those three will all work in much the same way. There may be some edge cases where intval() differs from the other two, but in general, they will turn a string into an int. In the absence of NaN, they all output 0 (zero) if the string is non numeric and can't be parsed. But this should be sufficient for most DB sanitation purposes.
If you really want a the NaN on error, the closest you'll get is null. You can get this using filter_var():
$value = filter_var(FALSE, FILTER_VALIDATE_INT, FILTER_NULL_ON_FAILURE);
If you just want to check that the string is numeric, the is_numeric() function can do that:
$bool = is_numeric($string);
However, it returns true for decimals and also for scientific notation, so may not be perfect for most situations. A better option is ctype_digit() which returns true if the string is made up only of digits:
$bool = ctype_digit($string);
If non e of this suits, there is always the regex option, using preg_match() or preg_replace(), but these are definitely overkill for this kind of scenario.
You can use regular expression as below
$int = (int) preg_replace('/\D/', '', $strNonNumeric);
OR
$int = (int) preg_replace('/[^0-9]/', '', $strNonNumeric);
You can use:
$string = "90"; //string
$myInt = (int) $string; //parse to int
I would recommend using FILTER_VALIDATE_INT Filter.
about Filters on php.net
You can also use sscanf (just like you do in C)
<?php
$str = "10";
sscanf($str, "%d", $intVal);
$intVal *= 10;
echo $intVal;
?>
Output:
100
Related
Suppose we have a string $str = "a"; and number $num = 2;
$str = 'a';
$num = 2;
echo $str*$num;
Output:
0
When performing arithmetic operations on a string operand, PHP will try to convert the string to a number.
It does this by looking for digits at the beginning of the string and will try to convert them into a value. If there are no digits, the value will be zero.
(There's an edge case for strings containing e or E (scientific notation), but that's not relevant here.)
Good Question.
Same i did ask to my teacher when i was in collage,
The answer is.
String * int= infinity; //According to scientific calculator answer is infinity.
but we need to continue our so program it provide 0.
it is made by code by default answer.
Simply said the string will be converted to an integer with a value of 0. This will include most of the cases when only alphabetic values are used. If you try to add a integer value at the beginning of the string it would in theory become a integer of that value.
I would recommend to read Why PHP Strings Equal Zero or Comparison Operators
Maybe you are looking for str_repeat, instead doing looping for that, its a default value that php serve to you, or you need to cast A into integer . When you try to do calculation for data that is not in Integer/float data type. Usually PHP auto-typecast the variables. In some cases it wont. Then we have to type cast it manually
This question already has answers here:
Unformat money when parsing in PHP
(8 answers)
Closed 7 years ago.
How to convert a string like "3,2563" to "3.2563",
$number = "3,2563" ;
setlocale(LC_MONETARY,"en_US");
echo money_format("%.4n", $number);
or
$number = number_format($number,4,".","");
Both examples output just 3.0000
The string "3,2563" is not a number, thus - it cannot be used as such.
It can easily be converted to a float number, using PHP function str_replace and type casting.
$number = "3,2563";
$number = (float)str_replace(",", ".", $number); // returns (float) 3.2563
// Do whatever you want to do. Now $number is a float.
Using str_replace, the , is replaced with a .
Note that the decimals separator can vary, depending on your PHP configuration.
"3,2563" is a string, you're trying to display a string as a number, that's not possible.
You can replace , with . before changing its type:
$number = "3,2563";
$number = str_replace(',', '.', $number); // get "3.2563"
$number = (float) $number; // get a floating number
setlocale(LC_MONETARY,"en_US");
echo money_format("%.4n", $number); // shows "3.2563"
echo money_format("%.2n", $number); // shows "3.26"
You're using a string ill-formatted for the desired use-case and existing logic you have in your code - i.e. '3,2563'. Let me be more clear. In some countries, a comma is used instead of a decimal to demarcate a whole unit of some currency and fractional units of some currency. In other cases, the comma and decimals indicate a thousand whole unit of some currency. It depends on what you're aiming for which isn't clear based on the example you gave... plus, I'm not aware of every monetary syntax convention.
In any event, the general procedure you want to employ is to remove all the commas or to normalize the number (for example use 32563 instead of 3,2563 if you're going for whole units), do your operations, and then reapply the convention (I assume that they're monetary conventions) that you want at the end. If you just want to replace the comma with a decimal - you can still use str_replace() to accomplish that as well. Build a function or class to do that so you can reuse that code for use with other similar problems.
My recommendation, though it wasn't explicit, is to simply use some str_replace() logic to generate a normalized/indexed number.
I have a string value from database.
I need to check if this value is an integer or a string.
I have tried is_int and is_numeric, but both of them are not what I need.
is_int always return false if the value is type of String while is_numeric return true if my the value contain number.
What I am using is preg_match('/^\d+$/',$value), and, I am looking for a simple solution in this case.
$stringIsAnInteger = ctype_digit($string);
ctyped_digit()
You can use ctype_digit() — Check for numeric character(s). Checks if all of the characters in the provided string, text, are numerical.
Example 1
<?php
$strings = array('1820.20', '10002', 'wsl!12');
foreach ($strings as $testcase) {
if (ctype_digit($testcase)) {
echo "The string $testcase consists of all digits.\n";
} else {
echo "The string $testcase does not consist of all digits.\n";
}
}
?>
Above will output
The string 1820.20 does not consist of all digits.
The string 10002 consists of all digits.
The string wsl!12 does not consist of all digits.
Example 2
<?php
$numeric_string = '42';
$integer = 42;
ctype_digit($numeric_string); // true
ctype_digit($integer); // false (ASCII 42 is the * character)
is_numeric($numeric_string); // true
is_numeric($integer); // true
?>
I find your way the best one.
I see nothing complex in a simple regex, so, in your place I wouldn't look for simpler.
Speaking of complexity, do not limit yourself just to the caller code.
It could be as short as a single function call. But you cannot be sure about underlying code, which can be enormously complex and - an important thing - have some issues, like every function named here does.
While your own solution either simple and robust.
Update:
All the remarks saying "do not use regexp where simple string function can be used for the performance blah-blah" are directly from the last century.
it doesn't mean "do not use regexp even if none of string functions suits you"
it's XXI at the moment, and computers are blazingly fast, especially in such easy matters as text parsing. Such a simple regexp will never be a bottleneck of your application. So, there is not a single reason to prefer a string function over regexp in terms of performance optimization. On a real life app you will never ever notice (or measure) any difference.
I've done some searching around and most posts are using the php explode function to separate a string and store its values into an array.
I need an efficient way to convert:
$string = "45,34,65,57,45,23,26,72,73,56";
To an array, so I can access single values using $array[3].
Is there a better method than explode?
Explode is the fastest method of splitting a string into an array, since it is a naive string reader searching for a delimiter. There is no regex engine overhead involved in this like with split/preg_split/ereg, etc. The only way you could improve performance would be splitting hairs on a mouse's back, and that would be to single quote your string array so that it's not parsed for variables.
However, given the size of your example array, you could calculate pi to the number of decimal places equivalent to the value of each number in the array and still not even scratch the surface of a performance problem.
$desiredPart = 3;
$num = strtok($string, ',');
$part = 1;
while ($part < $desiredPart && $num !== false) {
$num = strtok(',');
$part++;
}
echo $num;
This is probably the most efficient if you need to handle really long, and I mean really long, strings. For anything of the size you have posted as example, use explode.
If your parts are all the same length, just do:
$desiredPart = 3;
$partLength = 2;
$num = substr($string, ($partLength + 1) * ($desiredPart - 1), $partLength);
If the length of the parts is constant, you can check performance of the str_split method.
http://www.php.net/manual/en/function.str-split.php
You could use regular expression but that would be slower than explode()
The explode() method is quickest.
preg_split() is a more flexible alternative, but it's much slower.
whats wrong with explode?
you could use regex / substring, but those are slow in both development / runtime.
best of all, explode is done for you.
A select field on my HTML form may yield 1 to 5 (integers). Using is_int rejects it every time, because the $_POST['rating'] is viewed as a string.
After consulting the PHP Manual, it seems is_numeric() && !is_float() is the proper way to validate for an integer in this case.
But I want to be certain, so please confirm or fire away at my logic.
I would probably use something like this:
$value = filter_var(
$_POST['rating'],
FILTER_VALIDATE_INT,
array('options' => array('min_range' => 1, 'max_range' => 5)));
filter_var() will return either boolean false if the value is non-integer or out-of-range, or the valid value itself (as an integer.)
I would use is_numeric(), because user input always comes in as a string (as far as I know).
Another way to guarantee something is an integer is to cast it...
$id = (int) $id;
You could use the following regular expression:
preg_match('/^[0-9]{1,}$/', $value);
I does validate digits with leading zeros though...
if you want to know if $_POST['rating'] is an int before you even try to cast do use is_numeric() && !is_float() as you have. This will tell you if the string is an int or not. If you just cast to an int and there is a non numeric all the numbers before the first letter in the string is turned into an int.
x = 457h
print (int)x
outputs 457
x = h56
print (int)x
outputs 0
is_int requires the input content is a integer.
is_numeric requires the input content is a integer or a string including just 0-9.
but I am wondering the result if I put a number that is bigger than PHP_INT_MAX as the parameter into the above 2 functions.
You can always cast it as an int.
$rating = (int)$_POST['rating'];
This will remove the need to validate it (even though you should always validate form data).
It may reduce your steps is what I'm getting at.
If you're testing for digits only (what an integer usually is ;)), I tend to use ctype_digit instead of is_int. That way, you won't lose data through casting, and you can just use a string:
<?php
$_POST['foo'] = '42';
echo ctype_digit( (string) $_POST['foo'] ) ? 'yep' : 'nope';
That'll output "yep".