how to get length of integers in PHP ? - php

I want to get the length of integer values for validation in PHP.
Example:
Mobile numbers should be only 10 integer values. It should not be more than 10 or less than 10 and also it should not be included of alphabetic characters.
How can I validate this?

$num_length = strlen((string)$num);
if($num_length == 10) {
// Pass
} else {
// Fail
}

if (preg_match('/^\d{10}$/', $string)) {
// pass
} else {
// fail
}

This will work for almost all cases (except zero) and easily coded in other languages:
$length = ceil(log10(abs($number) + 1));

In my opinion, the best way is:
$length = ceil(log10($number))
A decimal logarithm rounded up is equal to length of a number.

If you are using a web form, make sure you limit the text input to only hold 10 characters as well to add some accessibility (users don't want to input it wrong, submit, get a dialog about their mistake, fix it, submit again, etc.)

Use intval function in loop,
See this example
<?php
$value = 16432;
$length=0;
while($value!=0) {
$value = intval($value/10);
$length++
}
echo "Length of Integer:- ".$length;
?>

$input = "03432 123-456"; // A mobile number (this would fail)
$number = preg_replace("/^\d/", "", $number);
$length = strlen((string) $number);
if ($number == $input && $length == 10) {
// Pass
} else {
// Fail
}

If you are evaluating mobile numbers (phone numbers) then I would recommend not using an int as your chosen data type. Use a string instead because I cannot forsee how or why you would want to do math with these numbers. As a best practice, use int, floats, etc, when you want/need to do math. Use strings when you don't.

From your question, "You want to get the lenght of an integer, the input will not accept alpha numeric data and the lenght of the integer cannot exceed 10. If this is what you mean; In my own opinion, this is the best way to achieve that:"
<?php
$int = 1234567890; //The integer variable
//Check if the variable $int is an integer:
if (!filter_var($int, FILTER_VALIDATE_INT)) {
echo "Only integer values are required!";
exit();
} else {
// Convert the integer to array
$int_array = array_map('intval', str_split($int));
//get the lenght of the array
$int_lenght = count($int_array);
}
//Check to make sure the lenght of the int does not exceed or less than10
if ($int_lenght != 10) {
echo "Only 10 digit numbers are allow!";
exit();
} else {
echo $int. " is an integer and its lenght is exactly " . $int_lenght;
//Then proceed with your code
}
//This will result to: 1234556789 is an integer and its lenght is exactly 10
?>

By using the assertion library of Webmozart Assert we can use their build-in methods to validate the input.
Use integerish() to validate that a value casts to an integer
Use length() to validate that a string has a certain number of characters
Example
Assert::integerish($input);
Assert::length((string) $input, 10); // expects string, so we type cast to string
As all assertions in the Assert class throw an Webmozart\Assert\InvalidArgumentException if they fail, we can catch it and communicate a clear message to the user.
Example
try {
Assert::integerish($input);
Assert::length((string) $input, 10);
} catch (InvalidArgumentException) {
throw new Exception('Please enter a valid phone number');
}
As an extra, it's even possible to check if the value is not a non-negative integer.
Example
try {
Assert::natural($input);
} catch (InvalidArgumentException) {
throw new Exception('Please enter a valid phone number');
}
I hope it helps 🙂

A bit optimazed answer in 2 or 3 steps depends if we allow negative value
if(is_int($number)
&& strlen((string)$number) == 10)
{
// 1 000 000 000 Executions take from 00:00:00.153200 to 00:00:00.173900
//Code
}
Note that will allow negative up to 9 numbers like -999999999
So if we need skip negatives we need 3rd comparision
if(is_int($number)
&& $number >= 0
&& strlen((string)$number) == 10)
{
// 1 000 000 000 Executions take from 00:00:00.153200
// to 00:00:00.173900 over 20 tests
}
Last case when we want from -1 000 000 000 to 1 000 000 000
if(is_int($number)
&& $number >= 0
&& strlen(str_replace('-', '', (string)$number)) == 10)
{
// 1 000 000 000 Executions take from 00:00:00.153200
// to 00:00:00.173900 over 20 tests
}
For compare
First naswer with regex
if (preg_match('/^\d{10}$/', $number)) {
// Fastest test with 00:00:00.246200
}
** Tested at PHP 8.0.12
** XAMPP 3.3.0
** Ryzen 7 2700
** MSI Radeon RX 5700 8G
Tested like
$function = function($number)
{
if(is_int($number)
&& $number >= 0
&& strlen((string)$number) == 10)
{
return true;
}
}
$number = 1000000000;
$startTime = DateTime::createFromFormat('U.u', microtime(true);
for($i = 0; $i < 1000000000; $i++)
{
call_user_func_array($function, $args);
}
$endTime = DateTime::createFromFormat('U.u', microtime(true);
echo $endTime->diff($startTime)->format('%H:%I:%S.%F');

Related

Convert Thousands in K format to regular Thousands format

I have numbers that are given to me in the following format:
12.2K
I would instead like to convert this number to display:
12200
The examples ive seen convert to K format, but I would like to convert from K format.
Is there an easy way to do this?
Thanks!
You mean, something like this? This will be able to convert thousands and millions, etc.
<?php
$s = "12.2K";
if (strpos(strtoupper($s), "K") != false) {
$s = rtrim($s, "kK");
echo floatval($s) * 1000;
} else if (strpos(strtoupper($s), "M") != false) {
$s = rtrim($s, "mM");
echo floatval($s) * 1000000;
} else {
echo floatval($s);
}
?>
<?php
$number = '12.2K';
if (strpos($number, 'K') !== false)
{
$number = rtrim($number, 'K') * 1000;
}
echo $number
?>
Basically, you just want to check if the string contains a certain character, and if it does, respond to it by taking it out and multiplying it by 1000.
An alternative method is to have the abbreviations in an array and use power of to calculate the number to multiply with.
This gives a shorter code if you have lots of abbreviations.
I use strtoupper to make sure it matches both k and K.
$arr = ["K" => 1 ,"M" => 2, "T" => 3]; // and so on for how ever long you need
$input = "12.2K";
if(isset($arr[strtoupper(substr($input, -1))])){ //does the last character exist in array as an key
echo substr($input,0,-1) * pow(1000, $arr[strtoupper(substr($input, -1))]); //multiply with the power of the value in array
// 12.2 * 1000^1
}else{
echo $input; // less than 1k, just output
}
https://3v4l.org/LXVXN
$result = str_ireplace(['.', 'K'], ['', '00'], '12.2K');
You can also expand this by other letters etc.

Finding where a variable has a decimal [duplicate]

I need to check in PHP if user entered a decimal number (US way, with decimal point: X.XXX)
Any reliable way to do this?
You can get most of what you want from is_float, but if you really need to know whether it has a decimal in it, your function above isn't terribly far (albeit the wrong language):
function is_decimal( $val )
{
return is_numeric( $val ) && floor( $val ) != $val;
}
if you want "10.00" to return true check Night Owl's answer
If you want to know if the decimals has a value you can use this answer.
Works with all kind of types (int, float, string)
if(fmod($val, 1) !== 0.00){
// your code if its decimals has a value
} else {
// your code if the decimals are .00, or is an integer
}
Examples:
(fmod(1.00, 1) !== 0.00) // returns false
(fmod(2, 1) !== 0.00) // returns false
(fmod(3.01, 1) !== 0.00) // returns true
(fmod(4.33333, 1) !== 0.00) // returns true
(fmod(5.00000, 1) !== 0.00) // returns false
(fmod('6.50', 1) !== 0.00) // returns true
Explanation:
fmod returns the floating point remainder (modulo) of the division of the arguments, (hence the (!== 0.00))
Modulus operator - why not use the modulus operator? E.g. ($val % 1 != 0)
From the PHP docs:
Operands of modulus are converted to integers (by stripping the decimal part) before processing.
Which will effectively destroys the op purpose, in other languages like javascript you can use the modulus operator
If all you need to know is whether a decimal point exists in a variable then this will get the job done...
function containsDecimal( $value ) {
if ( strpos( $value, "." ) !== false ) {
return true;
}
return false;
}
This isn't a very elegant solution but it works with strings and floats.
Make sure to use !== and not != in the strpos test or you will get incorrect results.
another way to solve this: preg_match('/^\d+\.\d+$/',$number); :)
The function you posted is just not PHP.
Have a look at is_float [docs].
Edit: I missed the "user entered value" part. In this case you can actually use a regular expression:
^\d+\.\d+$
I was passed a string, and wanted to know if it was a decimal or not. I ended up with this:
function isDecimal($value)
{
return ((float) $value !== floor($value));
}
I ran a bunch of test including decimals and non-decimals on both sides of zero, and it seemed to work.
is_numeric returns true for decimals and integers. So if your user lazily enters 1 instead of 1.00 it will still return true:
echo is_numeric(1); // true
echo is_numeric(1.00); // true
You may wish to convert the integer to a decimal with PHP, or let your database do it for you.
This is a more tolerate way to handle this with user input. This regex will match both "100" or "100.1" but doesn't allow for negative numbers.
/^(\d+)(\.\d+)?$/
// if numeric
if (is_numeric($field)) {
$whole = floor($field);
$fraction = $field - $whole;
// if decimal
if ($fraction > 0)
// do sth
else
// if integer
// do sth
}
else
// if non-numeric
// do sth
i use this:
function is_decimal ($price){
$value= trim($price); // trim space keys
$value= is_numeric($value); // validate numeric and numeric string, e.g., 12.00, 1e00, 123; but not -123
$value= preg_match('/^\d$/', $value); // only allow any digit e.g., 0,1,2,3,4,5,6,7,8,9. This will eliminate the numeric string, e.g., 1e00
$value= round($value, 2); // to a specified number of decimal places.e.g., 1.12345=> 1.12
return $value;
}
$lat = '-25.3654';
if(preg_match('/./',$lat)) {
echo "\nYes its a decimal value\n";
}
else{
echo 'No its not a decimal value';
}
A total cludge.. but hey it works !
$numpart = explode(".", $sumnum);
if ((exists($numpart[1]) && ($numpart[1] > 0 )){
// it's a decimal that is greater than zero
} else {
// its not a decimal, or the decimal is zero
}
the easy way to find either posted value is integer and float so this will help you
$postedValue = $this->input->post('value');
if(is_numeric( $postedValue ) && floor( $postedValue ))
{
echo 'success';
}
else
{
echo 'unsuccess';
}
if you give 10 or 10.5 or 10.0 the result will be success if you define any character or specail character without dot it will give unsuccess
How about (int)$value != $value?
If true it's decimal, if false it's not.
I can't comment, but I have this interesting behaviour.
(tested on v. 7.3.19 on a website for php testing online)
If you multiply 50 by 1.1 fmod gives different results than expected.
If you do by 1.2 or 1.3 it's fine, if you do another number (like 60 or 40) is also fine.
$price = 50;
$price = $price * 1.1;
if(strpos($price,".") !== false){
echo "decimal";
}else{
echo "not a decimal";
}
echo '<br />';
if(fmod($price, 1) !== 0.00){
//echo fmod($price, 1);
echo "decimal";
} else {
echo "not a decimal";
}//end if
Simplest solution is
if(is_float(2.3)){
echo 'true';
}
If you are working with form validation. Then in this case form send string.
I used following code to check either form input is a decimal number or not.
I hope this will work for you too.
function is_decimal($input = '') {
$alphabets = str_split($input);
$find = array('0','1','2','3','4','5','6','7','8','9','.'); // Please note: All intiger numbers are decimal. If you want to check numbers without point "." then you can remove '.' from array.
foreach ($alphabets as $key => $alphabet) {
if (!in_array($alphabet, $find)) {
return false;
}
}
// Check if user has enter "." point more then once.
if (substr_count($input, ".") > 1) {
return false;
}
return true;
}
function is_decimal_value( $a ) {
$d=0; $i=0;
$b= str_split(trim($a.""));
foreach ( $b as $c ) {
if ( $i==0 && strpos($c,"-") ) continue;
$i++;
if ( is_numeric($c) ) continue;
if ( stripos($c,".") === 0 ) {
$d++;
if ( $d > 1 ) return FALSE;
else continue;
} else
return FALSE;
}
return TRUE;
}
Known Issues with the above function:
1) Does not support "scientific notation" (1.23E-123), fiscal (leading $ or other) or "Trailing f" (C++ style floats) or "trailing currency" (USD, GBP etc)
2) False positive on string filenames that match a decimal: Please note that for example "10.0" as a filename cannot be distinguished from the decimal, so if you are attempting to detect a type from a string alone, and a filename matches a decimal name and has no path included, it will be impossible to discern.
Maybe try looking into this as well
!is_int()

How to get number of digits in both right, left sides of a decimal number

I wonder if is there a good way to get the number of digits in right/left side of a decimal number PHP. For example:
12345.789 -> RIGHT SIDE LENGTH IS 3 / LEFT SIDE LENGTH IS 5
I know it is readily attainable by helping string functions and exploding the number. I mean is there a mathematically or programmatically way to perform it better than string manipulations.
Your answers would be greatly appreciated.
Update
The best solution for left side till now was:
$left = floor(log10($x))+1;
but still no sufficient for right side.
Still waiting ...
To get the digits on the left side you can do this:
$left = floor(log10($x))+1;
This uses the base 10 logarithm to get the number of digits.
The right side is harder. A simple approach would look like this, but due to floating point numbers, it would often fail:
$decimal = $x - floor($x);
$right = 0;
while (floor($decimal) != $decimal) {
$right++;
$decimal *= 10; //will bring in floating point 'noise' over time
}
This will loop through multiplying by 10 until there are no digits past the decimal. That is tested with floor($decimal) != $decimal.
However, as Ali points out, giving it the number 155.11 (a hard to represent digit in binary) results in a answer of 14. This is because as the number is stored as something like 155.11000000000001 with the 32 bits of floating precision we have.
So instead, a more robust solution is needed. (PoPoFibo's solutions above is particularly elegant, and uses PHPs inherit float comparison functions well).
The fact is, we can never distinguish between input of 155.11 and 155.11000000000001. We will never know which number was originally given. They will both be represented the same. However, if we define the number of zeroes that we can see in a row before we just decide the decimal is 'done' than we can come up with a solution:
$x = 155.11; //the number we are testing
$LIMIT = 10; //number of zeroes in a row until we say 'enough'
$right = 0; //number of digits we've checked
$empty = 0; //number of zeroes we've seen in a row
while (floor($x) != $x) {
$right++;
$base = floor($x); //so we can see what the next digit is;
$x *= 10;
$base *= 10;
$digit = floor($x) - $base; //the digit we are dealing with
if ($digit == 0) {
$empty += 1;
if ($empty == $LIMIT) {
$right -= $empty; //don't count all those zeroes
break; // exit the loop, we're done
}
} else {
$zeros = 0;
}
}
This should find the solution given the reasonable assumption that 10 zeroes in a row means any other digits just don't matter.
However, I still like PopoFibo's solution better, as without any multiplication, PHPs default comparison functions effectively do the same thing, without the messiness.
I am lost on PHP semantics big time but I guess the following would serve your purpose without the String usage (that is at least how I would do in Java but hopefully cleaner):
Working code here: http://ideone.com/7BnsR3
Non-string solution (only Math)
Left side is resolved hence taking the cue from your question update:
$value = 12343525.34541;
$left = floor(log10($value))+1;
echo($left);
$num = floatval($value);
$right = 0;
while($num != round($num, $right)) {
$right++;
}
echo($right);
Prints
85
8 for the LHS and 5 for the RHS.
Since I'm taking a floatval that would make 155.0 as 0 RHS which I think is valid and can be resolved by String functions.
php > $num = 12345.789;
php > $left = strlen(floor($num));
php > $right = strlen($num - floor($num));
php > echo "$left / $right\n";
5 / 16 <--- 16 digits, huh?
php > $parts = explode('.', $num);
php > var_dump($parts);
array(2) {
[0]=>
string(5) "12345"
[1]=>
string(3) "789"
As you can see, floats aren't the easiest to deal with... Doing it "mathematically" leads to bad results. Doing it by strings works, but makes you feel dirty.
$number = 12345.789;
list($whole, $fraction) = sscanf($number, "%d.%d");
This will always work, even if $number is an integer and you’ll get two real integers returned. Length is best done with strlen() even for integer values. The proposed log10() approach won't work for 10, 100, 1000, … as you might expect.
// 5 - 3
echo strlen($whole) , " - " , strlen($fraction);
If you really, really want to get the length without calling any string function here you go. But it's totally not efficient at all compared to strlen().
/**
* Get integer length.
*
* #param integer $integer
* The integer to count.
* #param boolean $count_zero [optional]
* Whether 0 is to be counted or not, defaults to FALSE.
* #return integer
* The integer's length.
*/
function get_int_length($integer, $count_zero = false) {
// 0 would be 1 in string mode! Highly depends on use case.
if ($count_zero === false && $integer === 0) {
return 0;
}
return floor(log10(abs($integer))) + 1;
}
// 5 - 3
echo get_int_length($whole) , " - " , get_int_length($fraction);
The above will correctly count the result of 1 / 3, but be aware that the precision is important.
$number = 1 / 3;
// Above code outputs
// string : 1 - 10
// math : 0 - 10
$number = bcdiv(1, 3);
// Above code outputs
// string : 1 - 0 <-- oops
// math : 0 - INF <-- 8-)
No problem there.
I would like to apply a simple logic.
<?php
$num=12345.789;
$num_str="".$num; // Converting number to string
$array=explode('.',$num_str); //Explode number (String) with .
echo "Left side length : ".intval(strlen($array[0])); // $array[0] contains left hand side then check the string length
echo "<br>";
if(sizeof($array)>1)
{
echo "Left side length : ".intval(strlen($array[1]));// $array[1] contains left hand check the string length side
}
?>

Issues with integer operations

function sendSms($toPhone,$message){
$toPhone=intval(trim($toPhone));
if(strlen($toPhone)== 8 && $toPhone{0}==9){
//sending sms
}else{
return "error";
}
}
I am trying to validate mobile numbers for sending SMS. The first line trims the phone number string and then converts it to an integer. In the if statement, I want to make sure that the number length is 8 digits and it begins with 9. This function always goes for the else even if the number is correct( 8 digits and begins with 9). What could be the issue here.
Why not regex?
$valid = preg_match('/^9[0-9]{7}$/', trim($phone));
You can remove from $toPhone all not digits
function sendSms($toPhone,$message){
$_phone = '';
for ($i = 0; $i < strlen($toPhone); $i++)
{
if (is_numeric($toPhone[$i]))
$_phone .= $toPhone[$i];
}
if(strlen($_phone)== 8 && $_phone[0]=='9'){
//sending sms
}else{
return "error";
}
}
After you converted the phone number to an integer with $toPhone=intval(trim($toPhone));,, you can't access the digits in the way you are trying with $toPhone{0}, because you operate on a number and not on a string any more.
See this isolated example:
$number = 987654321;
var_dump($number{0}); //NULL
However, substr would be capable of doing this:
$number = 987654321;
var_dump(substr($number, 0, 1)); //string(1) "9"
Converting a whole number to integer isn't a good idea anyways, because users might enter the number with spaces in between or signs like + and /. Better search for an already existing approach to validate phone numbers.
Take a look here, where the topic "validate mobile phone numbers" is covered in more detail: A comprehensive regex for phone number validation
You convert variable to integer and apparently $toPhone[0] works on strings only.
The same function without intval() works as you wanted.
function sendSms($toPhone, $message)
{
$toPhone = trim($toPhone);
if(strlen($toPhone) == 8 && $toPhone[0] == 9){
//sending sms
} else {
return "error";
}
}

Check if number is decimal

I need to check in PHP if user entered a decimal number (US way, with decimal point: X.XXX)
Any reliable way to do this?
You can get most of what you want from is_float, but if you really need to know whether it has a decimal in it, your function above isn't terribly far (albeit the wrong language):
function is_decimal( $val )
{
return is_numeric( $val ) && floor( $val ) != $val;
}
if you want "10.00" to return true check Night Owl's answer
If you want to know if the decimals has a value you can use this answer.
Works with all kind of types (int, float, string)
if(fmod($val, 1) !== 0.00){
// your code if its decimals has a value
} else {
// your code if the decimals are .00, or is an integer
}
Examples:
(fmod(1.00, 1) !== 0.00) // returns false
(fmod(2, 1) !== 0.00) // returns false
(fmod(3.01, 1) !== 0.00) // returns true
(fmod(4.33333, 1) !== 0.00) // returns true
(fmod(5.00000, 1) !== 0.00) // returns false
(fmod('6.50', 1) !== 0.00) // returns true
Explanation:
fmod returns the floating point remainder (modulo) of the division of the arguments, (hence the (!== 0.00))
Modulus operator - why not use the modulus operator? E.g. ($val % 1 != 0)
From the PHP docs:
Operands of modulus are converted to integers (by stripping the decimal part) before processing.
Which will effectively destroys the op purpose, in other languages like javascript you can use the modulus operator
If all you need to know is whether a decimal point exists in a variable then this will get the job done...
function containsDecimal( $value ) {
if ( strpos( $value, "." ) !== false ) {
return true;
}
return false;
}
This isn't a very elegant solution but it works with strings and floats.
Make sure to use !== and not != in the strpos test or you will get incorrect results.
another way to solve this: preg_match('/^\d+\.\d+$/',$number); :)
The function you posted is just not PHP.
Have a look at is_float [docs].
Edit: I missed the "user entered value" part. In this case you can actually use a regular expression:
^\d+\.\d+$
I was passed a string, and wanted to know if it was a decimal or not. I ended up with this:
function isDecimal($value)
{
return ((float) $value !== floor($value));
}
I ran a bunch of test including decimals and non-decimals on both sides of zero, and it seemed to work.
is_numeric returns true for decimals and integers. So if your user lazily enters 1 instead of 1.00 it will still return true:
echo is_numeric(1); // true
echo is_numeric(1.00); // true
You may wish to convert the integer to a decimal with PHP, or let your database do it for you.
This is a more tolerate way to handle this with user input. This regex will match both "100" or "100.1" but doesn't allow for negative numbers.
/^(\d+)(\.\d+)?$/
// if numeric
if (is_numeric($field)) {
$whole = floor($field);
$fraction = $field - $whole;
// if decimal
if ($fraction > 0)
// do sth
else
// if integer
// do sth
}
else
// if non-numeric
// do sth
i use this:
function is_decimal ($price){
$value= trim($price); // trim space keys
$value= is_numeric($value); // validate numeric and numeric string, e.g., 12.00, 1e00, 123; but not -123
$value= preg_match('/^\d$/', $value); // only allow any digit e.g., 0,1,2,3,4,5,6,7,8,9. This will eliminate the numeric string, e.g., 1e00
$value= round($value, 2); // to a specified number of decimal places.e.g., 1.12345=> 1.12
return $value;
}
$lat = '-25.3654';
if(preg_match('/./',$lat)) {
echo "\nYes its a decimal value\n";
}
else{
echo 'No its not a decimal value';
}
A total cludge.. but hey it works !
$numpart = explode(".", $sumnum);
if ((exists($numpart[1]) && ($numpart[1] > 0 )){
// it's a decimal that is greater than zero
} else {
// its not a decimal, or the decimal is zero
}
the easy way to find either posted value is integer and float so this will help you
$postedValue = $this->input->post('value');
if(is_numeric( $postedValue ) && floor( $postedValue ))
{
echo 'success';
}
else
{
echo 'unsuccess';
}
if you give 10 or 10.5 or 10.0 the result will be success if you define any character or specail character without dot it will give unsuccess
How about (int)$value != $value?
If true it's decimal, if false it's not.
I can't comment, but I have this interesting behaviour.
(tested on v. 7.3.19 on a website for php testing online)
If you multiply 50 by 1.1 fmod gives different results than expected.
If you do by 1.2 or 1.3 it's fine, if you do another number (like 60 or 40) is also fine.
$price = 50;
$price = $price * 1.1;
if(strpos($price,".") !== false){
echo "decimal";
}else{
echo "not a decimal";
}
echo '<br />';
if(fmod($price, 1) !== 0.00){
//echo fmod($price, 1);
echo "decimal";
} else {
echo "not a decimal";
}//end if
Simplest solution is
if(is_float(2.3)){
echo 'true';
}
If you are working with form validation. Then in this case form send string.
I used following code to check either form input is a decimal number or not.
I hope this will work for you too.
function is_decimal($input = '') {
$alphabets = str_split($input);
$find = array('0','1','2','3','4','5','6','7','8','9','.'); // Please note: All intiger numbers are decimal. If you want to check numbers without point "." then you can remove '.' from array.
foreach ($alphabets as $key => $alphabet) {
if (!in_array($alphabet, $find)) {
return false;
}
}
// Check if user has enter "." point more then once.
if (substr_count($input, ".") > 1) {
return false;
}
return true;
}
function is_decimal_value( $a ) {
$d=0; $i=0;
$b= str_split(trim($a.""));
foreach ( $b as $c ) {
if ( $i==0 && strpos($c,"-") ) continue;
$i++;
if ( is_numeric($c) ) continue;
if ( stripos($c,".") === 0 ) {
$d++;
if ( $d > 1 ) return FALSE;
else continue;
} else
return FALSE;
}
return TRUE;
}
Known Issues with the above function:
1) Does not support "scientific notation" (1.23E-123), fiscal (leading $ or other) or "Trailing f" (C++ style floats) or "trailing currency" (USD, GBP etc)
2) False positive on string filenames that match a decimal: Please note that for example "10.0" as a filename cannot be distinguished from the decimal, so if you are attempting to detect a type from a string alone, and a filename matches a decimal name and has no path included, it will be impossible to discern.
Maybe try looking into this as well
!is_int()

Categories