Page 1 of 1

Code for checking if a string is a number

Posted: Fri Jul 09, 2004 5:01 am
by tores
Bech100 | Please use

Code: Select all

tags when posting code. Read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url][/color]

This code checks whether a string is a number.
U are free to use it if u want...
If anyone got other suggestions, views etc. u could post it here.

Regards tores

Code: Select all

<?php
      $string = "0123456789";
      $number = true;
      // PHP4 & PHP5:
      $chars = preg_split('//', $string, -1, PREG_SPLIT_NO_EMPTY);
      // PHP5:
      //$chars = str_split($string);
      foreach($chars as $char){
	/* Ascii-values: '0' = 48, ... , '9' = 57 */
	for($i = 48; $i < 58; $i++){
	  if(ord($char) == $i){
	    $number = true;;
	    break; // break for...
	  }else{
	    $number = false;
	  }
	}
	if(!$number){
	  echo $string." is not a number!<br>";
	  break; // break foreach...
	}
      }
      if($number)
	echo $string." is a number!<br>";
?>

Posted: Fri Jul 09, 2004 5:11 am
by markl999
Couldn't you just do:

Code: Select all

if(ctype_digit($number)){
    echo 'Its a number';
} else {
    echo 'Its not a number';
}
:o

Posted: Fri Jul 09, 2004 5:22 am
by JayBird
Yup, thats how i would do it too Mark.

Anything along these lines, i would always look into it before creating a funtion like this. Usually you will save yourself a lot of time.

Mark

Posted: Fri Jul 09, 2004 5:22 am
by tores
Didn't know about the ctype_digit function. It certainly is a lot easier to use :)

Posted: Fri Jul 09, 2004 11:16 am
by Weirdan
[php_man]is_numeric[/php_man]:

Code: Select all

echo is_numeric($string) ? "numeric" : "some crap" ;
:lol:

Posted: Fri Jul 09, 2004 1:06 pm
by m3mn0n
Yeah you should check out the Strings section of the manual very carefully before making functions to do things in PHP. The function might already be there just waiting for you to exploit it to it's full potential. :)