473,840 Members | 1,631 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Test whether string is valid integer

Given a string variable (form input), how can I determine whether it
represents a valid integer?

is_numeric is true for floats as well as integers, and is_int always
fails on a string.

P.
Jul 17 '05 #1
6 6656
Paul E Collins wrote:
Given a string variable (form input), how can I determine whether it
represents a valid integer?

is_numeric is true for floats as well as integers, and is_int always
fails on a string.

P.


intval( $string ) == $string

works for me...
--
Rutger Claes rg*@rgc.tld
Replace tld with top level domain of belgium to contact me pgp:0x3B7D6BD6
From listening comes wisdom and from speaking repentance.

Jul 17 '05 #2
"Paul E Collins" <fi************ ******@CL4.org> wrote:
Given a string variable (form input), how can I
determine whether it represents a valid integer?


Okay, I've come up with a solution:

function isInteger($x)
{
return ($x === (string) (int) $x);
}

It returns false if $x has leading zeros, but that doesn't matter for
my purposes.

P.
Jul 17 '05 #3
Rutger Claes wrote:
Paul E Collins wrote:

Given a string variable (form input), how can I determine whether it
represents a valid integer?

is_numeric is true for floats as well as integers, and is_int always
fails on a string.


intval( $string ) == $string

works for me...


Depends on how strict you need to be...

intval($n)==$n will return TRUE if you have a float like 5.0

However, if you use:

intval($n)===$n

Then the string '5' would fail...

If you need to reject floats, but need to use strings as well, you'll
really need to do something like this (pulled from something I did a
couple years ago):

/**
* input_intval
*
* Takes a variable and returns the integer value that corresponds
* to the value. If the value cannot be represented by an integer,
* FALSE is returned.
*
* @param $n [mixed] Value to check.
* @result Returns an integer value or FALSE. Check for FALSE using
* if(input_intval ($n)===FALSE) in case of integer < 0 being
* returned.
**/
function input_intval($n ){
if(is_numeric($ n)){
if(is_int($n)){
return $n;
}else{
// this is a float...
if(intval($n)== $n){
return $n;
}else{
return FALSE;
}
}
}else{
return FALSE;
}
}

--
Justin Koivisto - sp**@koivi.com
http://www.koivi.com
Jul 17 '05 #4
Justin Koivisto wrote:
Rutger Claes wrote:
Paul E Collins wrote:

Given a string variable (form input), how can I determine whether it
represents a valid integer?

is_numeric is true for floats as well as integers, and is_int always
fails on a string.

intval( $string ) == $string

works for me...

Depends on how strict you need to be...

intval($n)==$n will return TRUE if you have a float like 5.0

However, if you use:

intval($n)===$n

Then the string '5' would fail...

If you need to reject floats, but need to use strings as well, you'll
really need to do something like this (pulled from something I did a
couple years ago):

/**
* input_intval
*
* Takes a variable and returns the integer value that corresponds
* to the value. If the value cannot be represented by an integer,
* FALSE is returned.
*
* @param $n [mixed] Value to check.
* @result Returns an integer value or FALSE. Check for FALSE using
* if(input_intval ($n)===FALSE) in case of integer < 0 being
* returned.
**/
function input_intval($n ){
if(is_numeric($ n)){
if(is_int($n)){
return $n;
}else{
// this is a float...
if(intval($n)== $n){
return $n;


Sorry, that should have been:

return intval($n);

I was getting too far ahead of myself typing it out...
}else{
return FALSE;
}
}
}else{
return FALSE;
}
}

--
Justin Koivisto - sp**@koivi.com
http://www.koivi.com
Jul 17 '05 #5
Here is the code I use:

$integer = (int)$value;
if ((string)$value <> (string)$intege r) {
$this->errors[$field] = "Value is not an integer";
return $value;
} // if

--
Tony Marston

http://www.tonymarston.net
"Paul E Collins" <fi************ ******@CL4.org> wrote in message
news:cn******** **@titan.btinte rnet.com...
Given a string variable (form input), how can I determine whether it
represents a valid integer?

is_numeric is true for floats as well as integers, and is_int always fails
on a string.

P.

Jul 17 '05 #6
Paul E Collins wrote:
Given a string variable (form input), how can I determine whether it
represents a valid integer?

is_numeric is true for floats as well as integers, and is_int always
fails on a string.

P.


"Zero" sensitive function :) 5.0000 is integer 5.0001 is not...

<?php

function checkInteger($i nput) {

// Check type
if(is_integer($ input)) {
return true;
} // if

// Typecast
$in = (integer) $input;

// Check strlen
if(($in == $input) && (strlen($in) == strlen($input)) ) {
return true;

// No '.'?
} elseif(strpos($ input, '.') === false) {
return false;

// We have '.'
} else {

// One for dot, other for zeros
$dig_num = strlen($input) - strlen($in) - 1;

// Get zeros
$zeros = '.';
for($i = 0; $i < $dig_num; $i++) {
$zeros .= '0';
} // form

// Final check
return (string) $in . $zeros == $input ? true : false;

} // if

} // func checkInteger

// Test it with this code!
print checkInteger('5 .00000') ? 'OK, int' : 'Not OK';

?>
Jul 17 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
4196
by: lawrence | last post by:
Someone on www.php.net suggested using a seems_utf8() method to test text for UTF-8 character encoding but didn't specify how to write such a method. Can anyone suggest a test that might work? Something that maybe gives 90% confidence that a given block of text is or is not UTF-8 encoded?
10
199272
by: dave | last post by:
I am reading input from a form. I want to validate the input by making sure that the string is actually an integer. How would I do this? Do i need to convert it to a character array and break down each character and test it? or is there an easier way? Thanks. --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.720 / Virus Database: 476 - Release Date: 7/14/04
10
23303
by: Randell D. | last post by:
Folks, I have a box that expects numeric input - I'd like to test for it (yeah, I'll have service side checks too but also want client checks). How can I test that my input is numeric - and numeric could mean positive or negative floating numbers For example: return true for 1, 1.5, -1, -4.25 and return false for any other non-numeric input...
67
4497
by: Ike Naar | last post by:
Hi, Asking your advice on the following subject: Suppose I want to find out whether a given pointer (say, p) of type *T points to an element of a given array (say, a) of type T. A way to achieve this would be a linear search through the array: int ptrInArrSafe(T *p,T *a,int max) /* check whether p points to an element of a */
5
2592
by: Dmitry Martynov | last post by:
Consider I have the following construction "if(x is T) ...". How much this test cost? And I wonder how it is implemented. Can I gain in performace if I introduce virtual methods like "bool isIt...()" in my base class and then call them instead of using is-operator?
35
2592
by: Cor | last post by:
Hallo, I have promised Jay B yesterday to do some tests. The subject was a string evaluation that Jon had send in. Jay B was in doubt what was better because there was a discussion in the C# newsgroup on 25 September. The regular expressions where in that newsgroup too involved. I told yesterday night, to Jay that I would test all 4 methods and the stupid method I was thinking of the first time that night when I saw Jon's
17
5292
by: Petyr David | last post by:
Just looking for the simplest. right now my perl script returns an error messge to the user if the date string is invalid. would like to do this before accessing the server. TX
7
30223
by: laura | last post by:
Hi, I have a variable of type double. I need to know if there is an integer number store there. How can I test that ? I also have a default precision for doing this operation. Many thanks, Laura
0
9863
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10924
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10665
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10302
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7845
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7023
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4498
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4080
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3139
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.