Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg



PHP : Function Reference : Variable Handling Functions : is_numeric

is_numeric

Finds whether a variable is a number or a numeric string (PHP 4, PHP 5)
bool is_numeric ( mixed var )


Related Examples ( Source code ) » is_numeric



Code Examples / Notes » is_numeric

stew_wilde

When using the exec() function in php to execute anther php script, any command line arguments passed the script will lose their type association, regardless of whether they are numeric or not, the same seems to hold true for strings as well.
ie : two scripts test.php:
<?php
$val = trim($argv[1]);
echo is_string($val);
?>
and testwrapper.php:
<?php
$tmp = 5;
exec("php ./test.php ".$tmp);
?>
Executing testwrapper.php on the command line will echo nothing (ie false), and false will be returned regardless of any escaping of parameters or other such attempts to overcome this.  The solution then is to explicitly cast $val in test.php to be an int and then is_numeric will work.  But as stated the same test was performed using a string for $val and the is_string() function and the same thing occurs.  Not the end of the world, but something to be aware of :)


drew

What php at thefriedmans dot net said below about .5 returning false and .0.5 returning true isn't true, at least not for me on PHP 5.0.0.  The program:
<?php
echo (is_numeric('5') ? "true" : "false") . "\n";
echo (is_numeric('5.5') ? "true" : "false") . "\n";
echo (is_numeric('.5') ? "true" : "false") . "\n";
echo (is_numeric('.0.5') ? "true" : "false") . "\n";
?>
yields:
true
true
true
false
Just as I would expect.
Drew


andrea dot vacondio

Two simple functions using is_numeric:
<?php
function is_odd($num){
return (is_numeric($num)&($num&1));
}

function is_even($num){
return (is_numeric($num)&(!($num&1)));
}
//examples
echo "1: odd? ".(is_odd(1)? "TRUE": "FALSE")."<br />";
//is_numeric(0) returns true
echo "0: odd? ".(is_odd(0)? "TRUE": "FALSE")."<br />";
echo "6: odd? ".(is_odd(6)? "TRUE": "FALSE")."<br />";
echo "\"italy\": odd? ".(is_odd("italy")? "TRUE": "FALSE")."<br />";
echo "null: odd? ".(is_odd(null)? "TRUE": "FALSE")."<br /><br />";
echo "1: even? ".(is_even(1)? "TRUE": "FALSE")."<br />";  
echo "0: even? ".(is_even(0)? "TRUE": "FALSE")."<br />";
echo "6: even? ".(is_even(6)? "TRUE": "FALSE")."<br />";
echo "\"italy\": even? ".(is_even("italy")? "TRUE": "FALSE")."<br />";  
echo "null: even? ".(is_even(null)? "TRUE": "FALSE")."<br />";
?>
And here is the result:
1: odd? TRUE
0: odd? FALSE
6: odd? FALSE
"italy": odd? FALSE
null: odd? FALSE
1: even? FALSE
0: even? TRUE
6: even? TRUE
"italy": even? FALSE
null: even? FALSE


elwin van huissteden

To James holwell:
Maybe your function was more strickt, but profides FALSE to any numeric string that wasnt written in the English/American notition. To enable a person to use the both the English/American and the rest of the world's way:
<?php
 function my_is_numeric($value)
 {
  return (preg_match ("/\A(-){0, 1}([0-9]+)((,|.)[0-9]{3, 3})*((,|.)[0-9]){0, 1}([0-9]*)\z/" ,$value) == 1);
 }
?>
Other than that, i'd recommend using yours, if it works (i havent tested either yours or mine)
By using mine, there might be a slight chance to not being able to do calculations with the numeric string if it's not the English/American way.
(*Note:
-the E/A way of writing 1 million (with decimal for 1/50): 1,000,000.02
-the global way of writing 1 million (with decimal for 1/50): 1.000.000,02


php dot net

This is a little more explicit and won't break when the value can't be legally cast as an int
function is_intValued($var)
{
   // Determines if a variable's value is an integer regardless of type
   // meant to be an analogy to PHP's is_numeric()
   if (is_int($var)) return TRUE;
   if (is_string($var) and $var === (string)(int) $var) return TRUE;
   if (is_float($var) and $var === (float)(int) $var) return TRUE;
   else return FALSE;
}


titouthat

This function converts an input string into bool, int or float depending on its content.
<?php
function convert_type( $var )
{
if( is_numeric( $var ) )
{
if( (float)$var != (int)$var )
{
return (float)$var;
}
else
{
return (int)$var;
}
}

if( $var == "true" ) return true;
if( $var == "false" ) return false;

return $var;
}
?>
'90' return an int
'90.9' return a float
'true' return a bool
'90.0' return a int


stephen

The documentation is not completely precise here. is_numeric will also return true if the number begins with a decimal point  and/or a space, provided a number follows (rather than a letter or punctuation). So, it doesn't necessarily have to start with a digit.

blazatek

the best way to check whether
variable is numeric is to check its ascii code :)
function is_num($var)
{
for ($i=0;$i<strlen($var);$i++)
{
$ascii_code=ord($var[$i]);

if ($ascii_code >=49 && $asci_code <=57)
continue;
else
return false;
}

return true;
}
this function can be usefull if you wont to chec eg $_POST
function test_post($tab)
{

$post = array();
$post=$tab;
echo $tab["user_name"];
foreach ($post as $varname => $varvalue)
{
    if (empty($varvalue))
       {
        $post[$varname] = null;
     
       }elseif (is_num($varvalue))
       {
$post[$varname]=trim($varvalue);
$post[$varname]=strip_tags($varvalue);
$post[$varname]=intval($varvalue);
$post[$varname]=addslashes($varvalue);
}else
{
                 $post[$varname]=NULL;
}
    }
    }//forech
   return $post;
}


mariusads::at::helpedia.com

Test if a number is positive and contains only 0-9:
function is_number($number)
{
$text = (string)$number;
$textlen = strlen($text);
if ($textlen==0) return 0;
for ($i=0;$i < $textlen;$i++)
{ $ch = ord($text{$i});
  if (($ch<48) || ($ch>57)) return 0;
}
return 1;
}
returns
0 : number contain character outside 0-9
1 : valid number.


mdallaire

Sometimes, we need to have no letters in the number and is_numeric does not quit the job.
You can try it this ways to make sure of the number format:
   function new_is_unsigned_float($val) {
       $val=str_replace(" ","",trim($val));
       return eregi("^([0-9])+([\.|,]([0-9])*)?$",$val);
   }
   function new_is_unsigned_integer($val) {
       $val=str_replace(" ","",trim($val));
       return eregi("^([0-9])+$",$val);
   }
   function new_is_signed_float($val) {
       $val=str_replace(" ","",trim($val));
       return eregi("^-?([0-9])+([\.|,]([0-9])*)?$",$val);
   }
   function new_is_signed_integer($val) {
       $val=str_replace(" ","",trim($val));
       return eregi("^-?([0-9])+$",$val);
   }
It returns 1 if okay and returns nothing "" if it's bad number formating.


mjbraca

Some examples. Note that leading white space is OK, but not trailing white space, and there can't be white space between the "-" and the number.
is_numeric("1,000") = F
is_numeric("1e2")   = T
is_numeric("-1e-2") = T
is_numeric("1e2.3") = F
is_numeric("1.")    = T
is_numeric("1.2")   = T
is_numeric("1.2.3") = F
is_numeric("-1")    = T
is_numeric("- 1")   = F
is_numeric("--1")   = F
is_numeric("1-")    = F
is_numeric("1A")    = F
is_numeric(" 1")    = T
is_numeric("1 ")    = F


02-apr-2001 06:20

Seems that this function can only verify numbers up to 16 digits long. Eg:
1111111111111111111
A 19-digit number will return false.


lukesneeringer

Regarding renimar at yahoo's function to yield ordinal numbers, the function lacks one thing. It accounts for numbers in the teens only if the number is below 100. If you used this function and gave 212 as the input, it would give 212nd, and not 212th. (Also, checking for numbers between 11 and 13 is sufficient, since 14-19 yield th either way.)
Therefore,
<?php if ($num >= 11 and $num <= 19) ?>
should be changed to...
<?php if ($num % 100>= 11 and $num % 100 <= 13) ?>
It will then work perfectly all the time.
Here's the entire function with the one line changed:
<?php
function ordinalize($num) {
      if (!is_numeric($num))
              return $num;
      if ($num % 100 >= 11 and $num % 100 <= 13)
              return $num."th";
      elseif ( $num % 10 == 1 )
              return $num."st";
      elseif ( $num % 10 == 2 )
              return $num."nd";
      elseif ( $num % 10 == 3 )
              return $num."rd";
      else // $num % 10 == 0, 4-9
              return $num."th";
}
?>


sebu

Referring to previous post "Be aware if you use is_numeric() or is_float() after using set_locale(LC_ALL,'lang') or set_locale(LC_NUMERIC,'lang')":
This is totally wrong!
This was the example code:
-----
 set_locale(LC_NUMERIC,'fr');
 is_numeric(12.25); // Return False
 is_numeric(12,25); // Return True
 is_float(12.25); //Return False
 is_float(12,25); //Return True
-----
This is nonsense!
- set_locale() does not exist, you must use setlocale() instead
- you have to enclose 12,25 with quotes; otherwise PHP will think that
the function gets _two_ arguments: 12 and 25 (depending on PHP version and setup you may additionally get a PHP warning)
- if you don't enclose 12,25 with quotes the first argument will be the inspected value (12), the second value (25) is discarded. And is_numeric(12) and is_float(12) is always TRUE
Corrected Example:
----
 setlocale(LC_NUMERIC,'fr');
 is_numeric(12.25); // Return True
 is_numeric("12,25"); // Return False
 is_float(12.25); //Return True
 is_float("12,25"); //Return False
----
Remarks:
- is_float(12.25) is _always_ TRUE, 12.25 is a PHP language construct (a "value") and the way PHP interpretes files is definitely _not_ affected by the locale
- is_float("12,25") is _always_ FALSE, since is_float (other than is_numeric): if the argument is a string then is_float() always returns FALSE since it does a strict check for floats
And the corrected example shows: you get the _same_ results for every possible locale, is_numeric() does not depend on the locale.


kouber

Note that this function is not appropriate to check if "is_numeric" for very long strings. In fact, everything passed to this function is converted to long and then to a double. Anything greater than approximately 1.8e308 is too large for a double, so it becomes infinity, i.e. FALSE. What that means is that, for each string with more than 308 characters, is_numeric() will return FALSE, even if all chars are digits.
However, this behaviour is platform-specific.
http://www.php.net/manual/en/language.types.float.php
In such a case, it is suitable to use regular expressions:
function is_numeric_big($s=0) {
 return preg_match('/^-?\d+$/', $s);
}


alexander dot j dot summers

Note that the even simpler functions for checking if a variable contains an odd or even number below don't produce good results if you apply them to arguments which aren't numeric; I guess that was the idea of the originals.
e.g. using the functions defined in two posts below..
IS_ODD(null)  returns false
IS_EVEN(null) returns true
is_odd(null)    returns false
is_even(null)  returns false


meagar

Miero: Your function doesn't match some special cases: '+1', '-0', '+0', all of which are valid integers.  The easiest and most reliable way to get a definite integer match is with a regular expression:
function is_intval($value) {
    return 1 === preg_match('/^[+-]?[0-9]+$/', $value);
}
This has two "problems" based on your input:  it matches both '00' and '999999999999999999999999999999999' as valid integers.
I'm not sure why you wouldn't want to match "00".  Regardless of whether somebody entered it in a form by accident or on purpose, it /is/ a valid integer, and in most instances you should accept it.
The second value, "999..." is also a valid integer, even if PHPs internal int type isn't precise enough to represent it.


php

is_numeric() in php5 returns false for strings with a leading decimal point:
<?php
is_numeric('5'); // true
is_numeric('5.5'); // true
is_numeric('.5'); // false
// but...
is_numeric('.0.5'); // true
?>
In certain situations, it may be useful to prepend a '0' to the string you're verifying with is_numeric():
<?php
if (is_numeric('0' . $user_input)) // ...
?>


moskalyuk

is_numeric fails on the hex values greater than LONG_MAX, so having a large hex value parsed through is_numeric would result in FALSE being returned even though the value is a valid hex number

codeslinger

in version 4.3.10  I find the following
".73"  TRUE
"0.73"  TRUE
"+0.73"  TRUE
"+.73"   FALSE
I would not call it a bug, just something to be aware of.
-----
Also be aware that if you give php a huge number and then you convert it to a string you get  
"INF"
if you pass that to mySQL etc. you could have a problem...


james.holwell

In reply to www.kigoobe.com, a more strict expression is
<?php
 function my_is_numeric($value)
 {
   return (preg_match ("/^(-){0,1}([0-9]+)(,[0-9][0-9][0-9])*([.][0-9]){0,1}([0-9]*)$/", $value) == 1);
 }
?>
This will not match strings like -6,77.8,8 which are matched by the below expression, and instead requires a single decimal point, with at least one character following, and only permits comma-separation when the right hand side is a triplet.


martijnt

If you want to make sure that a variable contains only one or more numbers as in the range 0-9, you could use this:
eregi("[^0-9]",$var)
This checks your variable for anything that is NOT in the range 0-9.
If you use is_numeric() while checking an IP address, you should not be surprised if the following is accepted as a valid IP: 1e13.3.4.12e3 -> is_numeric() considers 1e13 and 12e3 as valid numeric values (which is correct).
Have fun.
Martijn Tigchelaar,
DataServe.


aulbach

If you want to check, if a string will be converted into the exactly same number, you have to test the following:
if ( (string)(int)$val === (string)$val ) ...
This is not the same as
if ( is_numeric($val) ) ...
cause
<?php
$a="0000001";
if ( is_numeric($a) ) echo "a is numeric";
if ( (string)(float)$a !== (string)$a) echo "a cannot be converted 100%-correctly";
?>
will output:
a is numeric
a cannot be converted 100%-correctly
Ok, ok, I know. This is a hysteric type-check. It depends on the type of application, if you use it. The aim should always be, that the user could be warned, if the value cannot be stored in the way, the user types it into.
Why? Therefore is the following example:
If you set
$a="1E+17";
the above script says that it is all right.
But then we want to convert to INT, not FLOAT. is_numeric() doesn't distinct between INT and FLOAT, so a is_numeric('1E+17') is true, but the Integer of it returns 1, which isn't perhaps, what the user expects.


www.kigoobe.com

If you are looking for a way to check if the user input is a number, either positive or negative, or a decimal value (but not with an e, as in is_numeric), the following can be used -
<?php
mynumber = "3" // 3 is a number
$mynumber = "3.3" // 3.3 is a number
$mynumber = "-3.3" // -3.3 is a number
$mynumber = "-0,3" // -0,3 is a number
$mynumber = "-0,3x" // -0,3x is not a number
if (preg_match ("/^([0-9.,-]+)$/", $mynumber)) {
    print $mynumber." is a number";
} else {
    print $mynumber." is not a number";
}
?>
I have added comma (,) as in many european number system, decimal is expressed with a comma, and not with a dot. Like, $100 is expressed as $100,00 instead of $100.00
if you don't need that, remove the (,) and, you can add any additional value that you need to add after the series 0-9.,-


carlos madeira

If I may, i think there is a simpler way to determine if a number is odd or even:
if( $number & 1 ) //Just check the last bit!
 echo 'It's odd!';
else
 echo 'It's even!';


namik

I needed a number_suffix function that takes numbers with thousand seperators (using number_format() function).  Note that this doesn't properly handle decimals.
Example:
<?= number_suffix('1,021') ?> returns: 1,021st
Also, increasing the range above the condition statements increases efficiency.  That's almost 20% of the numbers between 0 and 100 that get to end early.
<?
 function number_suffix($number)
 {
   // Validate and translate our input
   if ( is_numeric($number) )
   {
     // Get the last two digits (only once)
     $n = $number % 100;
   } else {
    // If the last two characters are numbers
    if ( preg_match( '/[0-9]?[0-9]$/', $number, $matches ) )
    {
      // Return the last one or two digits
      $n = array_pop($matches);
    } else {
      // Return the string, we can add a suffix to it
      return $number;
    }
   }
   // Skip the switch for as many numbers as possible.
   if ( $n > 3 && $n < 21 )
     return $number . 'th';
   // Determine the suffix for numbers ending in 1, 2 or 3, otherwise add a 'th'
   switch ( $n % 10 )
   {
     case '1': return $number . 'st';
     case '2': return $number . 'nd';
     case '3': return $number . 'rd';
     default:  return $number . 'th';
   }
 }
?>


tvali

I changed function sent by
"ealma@hotmail.com 18-May-2001 12:02"
a little bit (it should be faster now).
Here is some code that will detect large values for numeric and for PHP3.
function is_num($s) {
 for ($i=0; $i<strlen($s); $i++) {
   if (($s[$i]<'0') or ($s[$i]>'9')) {return false;}
 }
return true;
}
You can also check only the first char in string (($s[0])<'9')and($s[0]>'0')), since php converts string to numeric only from beginning to the last digit.


eagleflyer2

Hi !
Many of you may have experienced that the 'is_numeric' function seems to fail always when form entries are checked against their variable type. So the function seems to return  'false' even if the form entry was aparently a number or numeric string.
The solution is pretty simple and no subroutines or fancy operations are necessary to make the 'is_numeric' function usable for form entry checks:
Simply strip off all (invisible) characters that may be sent along with the value when submitting a form entry.
Just use the 'trim' function before 'is_numeric'.
Example:
$variable = trim($variable);
if (is_numeric($variable)
{...#do something#...}
else
{...#do something else#...}


rontarrant

Here's an even simpler pair of functions for finding out if a number is odd or even:
function IS_ODD($number) { return($number & 1); }
function IS_EVEN($number) { return(!($number & 1)); }
Test:
$myNumber = 151;
if(IS_ODD($myNumber))
echo("number is odd\n");
else
echo("number is NOT odd\n");
if(IS_even($myNumber))
echo("number is even\n");
else
echo("number is NOT even\n");
Results:
number is odd
number is NOT even


jamespam

Here's a function to determine if a variable represents a whole number:
function is_whole_number($var){
 return (is_numeric($var)&&(intval($var)==floatval($var)));
}
just simple stuff...
is_whole_number(2.00000000001); will return false
is_whole_number(2.00000000000); will return true


ja

Here is a simple function to recognize whether the value is a natural number: (Zero is often exclude from the natural numbers, that's why there's the second parameter.)
<?php
function is_natural($val, $acceptzero = false) {
$return = ((string)$val === (string)(int)$val);
if ($acceptzero)
 $base = 0;
else
 $base = 1;
if ($return && intval($val) < $base)
 $return = false;
return $return;
}
?>


joe

Here is a simple function that I found usefull for filtering user input into numbers. Basically, it attempts to fix fat fingering. For example:
$userString = "$654.4r5";
function numpass_filter($userString){  
   $money = explode(".", $userString);
   //now $money[0] = "$645" and $money[1] = "4r5"
   //next remove all characters save 0 though 9
   //in both elements of the array
   $dollars = eregi_replace("[^0-9]", null, $money[0]);
   $cents = eregi_replace("[^0-9]", null, $money[1]);
   //if there was a decimal in the original string, put it back
   if((string)$cents!=null){
       $cents = "." . $cents;
   }
  $result = $dollars . $cents;
   return($result);
}
The output in this case would be '654.45'.
Please note that this function will work properly unless the user fat fingers an extra decimal in the wrong place.


miero

function is_intval($a) {
   return ((string)$a === (string)(int)$a);
}
true for ("123", "0", "-1", 0, 11, 9011, 00, 0x12, true)
false for (" ", "", 1.1, "123.1", "00", "0x123", "123a", "ada", "--1", "999999999999999999999999999999999", false, null, '1 ')


kiss dot pal

function is_float_ex($pNum) {
   $num_chars=("0123456789.,+-");
   if (strlen(trim($pNum))==0)  // empty $pNum -> null
     return FALSE;
   else {
     $i=0;
     $f=1;  // modify
     $v=strlen($num_chars)-$f;
     while (($i<strlen($pNum)) && ($v>=0)) {
       $v=strlen($num_chars)-$f;
       while (($v>=0) && ($num_chars[$v]<>$pNum[$i]))
         $v--;
       if ($f==1) // Only first item + vagy -
         $f=3;
       if (($pNum[$i]=='.') ||
           ($pNum[$i]==','))
         $f=5;
       $i++;
     }
     if ($v<0)
       return FALSE;
     else
       return TRUE;
   }
 }


tenhamedo.net

For mariusads::at::helpedia.com
I believe this is mutch easyer:
function positive_number($nr) {
if(ereg("^[0-9]+$", $nr) && $nr > 0){
 return true;
 } else {
 return false;
}
}


maninblack00

blazatek at wp dot pl wrote a function to check POST inputs for ASCII-keys or smth like that. there was an error while filtering $varvalue (it was only the value of the last filter 'addslashes')
here's the corrected function:
<?
function is_num ($num) {
     // .....
}
function test_post($tab) {
  $post = array();
  $post = $tab;
  foreach ($post as $varname => $varvalue) {
      echo $tab[$varname];
      if (empty($varvalue)) {
                $post[$varname] = null;
      }
      elseif (is_num($varvalue)) {
                $varvalue=trim($varvalue);
                $varvalue=strip_tags($varvalue);    
                $varvalue=intval($varvalue);
                $post[$varname]=addslashes($varvalue);    
      }
      else {    
                $post[$varname]=NULL;
      }
  }//forech    
   return $post;
}
?>
hope that correction is correct ;)


kendsnyder

Be careful when using is_numeric() to escape SQL strings.  is_numeric('0123') returns true but 0123 without quotes cannot be inserted into SQL.  PHP interprets 0123 without quotes as a literal octal number; but SQL just throws a syntax error.
<?php
is_numeric('0123'); // true
is_numeric(0.123); // true
is_numeric('0.123'); // true
is_numeric(123); // true
is_numeric('123'); // true
is_numeric('foo'); // false
?>
Casting a value to float then string and comparing it to the original value cast as string as the same effect as is_numeric but returns false for numeric strings that begin with zero and have no decimal point.  Examples:
<?php
function isDecimalNumber($n) {
 return (string)(float)$n === (string)$n;
}
isDecimalNumber('0123'); // false
isDecimalNumber(0.123); // true
isDecimalNumber('0.123'); // true
isDecimalNumber(123); // true
isDecimalNumber('123'); // true
isDecimalNumber('foo'); // true
?>


redy dot r

Be aware if you use is_numeric() or is_float() after using set_locale(LC_ALL,'lang') or set_locale(LC_NUMERIC,'lang')
Example :
If at the beginning of your script, you declare :
<?php
set_locale(LC_NUMERIC,'fr');
?>
and after, you will get this :
<?php
is_numeric(12.25); // Return False
is_numeric(12,25); // Return True
is_float(12.25); //Return False
is_float(12,25); //Return True
?>
Because, for french language the decimal separator is ',' (Comma) instead of '.' (Dot).


gregory boshoff

As mentioned above use the ctype character type functions to determine a strings type as ctype is faster. ctype_digit has far better benchmarks than is_numeric.
// Example:
$num = '888';
if(ctype_digit($num) === TRUE):
echo 'The string variable $num contains the decimal value '.$num;
endif;


kenn

A side note, finding out if an integer is even or odd, given the integer = $i ...
if (($i % 2) == 0) // This will test TRUE if the integer is even.
  {
xxx insert code here xxx
  }


q1712

a regex doing the same as is_numeric() is:
"^((-?[0-9]*\.[0-9]+|[[:space:]]*[+-]?[0-9]+(\.[0-9]*)?)
([eE][+-]?[0-9]+)?|0x[0-9a-fA-F]+)$" (took me some testing to figure this out)
regex: "^(decimal|hex)$"
 decimal: "(base1|base2)(exponent)?"
   base1: "-?[0-9]*\.[0-9]+"
          if there are no prepanded spaces and no "+" the
          base may be any of "0", ".0", "0.0".
   base2: "[[:space:]]*[+-]?[0-9]+(\.[0-9]*)?"
          if there are empty spaces or a "+" prepanded the
          base may only be "0" or "0.0" (no idea why)
   exponent: "[eE][+-]?[0-9]+"
             the exponent is opional
 hex: "0x[0-9a-fA-F]+"
usage: preg_match("/regex/D", $str); or ereg("regex", $str);
Just to know what is_numeric() is doing. Of cause the regex should be much slower and is_numeric() also returns false if the number would be to big to fit into a double.


renimar no spam

A little function to ordinalize numbers using is_numeric() and accounting for the numbers in the teens.
<?php
function ordinalize($num) {
       if (!is_numeric($num))
               return $num;
       if ($num >= 11 and $num <= 19)
               return $num."th";
       elseif ( $num % 10 == 1 )
               return $num."st";
       elseif ( $num % 10 == 2 )
               return $num."nd";
       elseif ( $num % 10 == 3 )
               return $num."rd";
       else
               return $num."th";
}
// Demo
for ($i=1; $i<=25; $i++) {
       print ordinalize($i) . " ";
}
// The loop returns:
// 1st 2nd 3rd 4th 5th 6th 7th 8th 9th 10th 11th 12th
// 13th 14th 15th 16th 17th 18th 19th 20th 21st 22nd
// 23rd 24th 25th
?>


ishmaelmakitla

//hello mates I just wanted to bring this forth so that you may see what I have been to
I tried to validate a certain field (name ) on my project web site design so that the only field acceptable is alphabetic the problem was that it has to include a space as in "Makitla M.I"
now ctype_alpha returned false as this includes a space
the same with
<?
 if(!ctype_alpha($name)||!ctype_space($name))
?>
now this is what I did
<?
   $name=explode(" ",$name);//to get rid of space charecter
  $name=explode(".",$name)//to get rid of the dod
//finally I tested if the resulting $name is purely alphabetic
if(!ctype_alpha($name))
    {
       echo"the name entered contained some   unacceptable       charecters...please reenter";
    exit;
   }
//this solved my problem...hope this helps some of you!!
?>


andi_nrw

<?php
/* This function is not useful if you want
to check that someone has filled in only
numbers into a form because for example
4e4 and 444 are both "numeric".
I used a regular expression for this problem
and it works pretty good. Maybe it is a good
idea to write a function and then to use it.
$input_number = "444"; // Answer 1
$input_number = "44 "; // Answer 2
$input_number = "4 4"; // Answer 2
$input_number = "4e4"; // Answer 2
$input_number = "e44"; // Answer 2
$input_number = "e4e"; // Answer 2
$input_number = "abc"; // Answer 2
*/
$input_number = "444";
if (preg_match ("/^([0-9]+)$/", $input_number)) {
print "Answer 1";
} else {
print "Answer 2";
}
?>


Change Language


Follow Navioo On Twitter
debug_zval_dump
doubleval
empty
floatval
get_defined_vars
get_resource_type
gettype
import_request_variables
intval
is_array
is_binary
is_bool
is_buffer
is_callable
is_double
is_float
is_int
is_integer
is_long
is_null
is_numeric
is_object
is_real
is_resource
is_scalar
is_string
is_unicode
isset
print_r
serialize
settype
strval
unserialize
unset
var_dump
var_export
eXTReMe Tracker