Can anyone look at this simple piece of code and tell me why it's doing what it does as it has a bug and I can't see it. I'm checking the first piece of input in a data stream for loading into a table and my numeric test is going nuts!! Here it is:

function is_num($var)
{
print("var = ". $var . "\n");
print("varlength = ". strlen($var) . "\n");
for ($i=0;$i<strlen($var);$i++)
{
$ascii_code=ord($var[$i]);
print($ascii_code . "\n");
if ($ascii_code >=49 && $ascii_code <=57)
continue;
else
return false;
}
return true;
}
...
... read in the data
...
$rs = is_num($ar0); // Calling Code
if ($rs)
print("FALSE" . "\n");
else
print("TRUE" . "\n");

Here's some of the input:

Bergners|100|61701|BLOOMINGTON|IL|134,861|5,116
61701|BLOOMINGTON|IL|MC LEAN|37,240|1,950|0.0
61702|BLOOMINGTON|IL|MC LEAN|0|271|0.2
61704|BLOOMINGTON|IL|MC LEAN|35,851|1,212|1.6
61791|BLOOMINGTON|IL|MC LEAN|0|0|1.9
61710|BLOOMINGTON|IL|MC LEAN|0|8|1.9
61709|BLOOMINGTON|IL|MC LEAN|0|2|2.0
61790|NORMAL|IL|MC LEAN|0|10|2.2

and here's the output from the first 2 and at the 2nd one it goes out to lunch!!! Can't see the problem!!

var = Bergners
varlength = 8
66
TRUE

var = 61701
varlength = 5
54
49
55
48
TRUE

I've parsed for hidden characters and there are none! Cant process but 2 entries before I get problems with data integrity as the first Non numeric entry sets up part of the data used in the table when the numeric data is inserted, and when it reads a numeric as char, it messes up some fields and causes the data from the numeric entry be places in fields where the types don't match. It just doesn't make sense as to why it would process the first correctly and go out to lunch on the 2nd?

    how come you arent using [man]is_numeric[/man]? php provides a function to tell you if a variable is a number.

      Hey drew, in all honesty, don't have an answer. Probably I had this function that I thought worked so just didn't think about an alternative. Better news is I pitched the function in the bit bucket and your suggestion worked. Nothing like making it hard on ourselves is there!!! THANKS, your recommendation left some hair on my head!!

        good deal. the php manual is always your friend, www.php.net/manual. if you arent sure of a function type it in the search and it will return similar sounding things, or just browse the whole list. and there are always great user comments along with the functions to help answer some additional questions the manual may not have addressed.

          In this case, [man]ctype_digit/man is more appropriate, since you're looking for integers only.

            Write a Reply...