Code for checking if a string is a number

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
tores
Forum Contributor
Posts: 120
Joined: Fri Jun 18, 2004 3:04 am

Code for checking if a string is a number

Post 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>";
?>
User avatar
markl999
DevNet Resident
Posts: 1972
Joined: Thu Oct 16, 2003 5:49 pm
Location: Manchester (UK)

Post 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
User avatar
JayBird
Admin
Posts: 4524
Joined: Wed Aug 13, 2003 7:02 am
Location: York, UK
Contact:

Post 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
Last edited by JayBird on Fri Jul 09, 2004 5:23 am, edited 2 times in total.
tores
Forum Contributor
Posts: 120
Joined: Fri Jun 18, 2004 3:04 am

Post by tores »

Didn't know about the ctype_digit function. It certainly is a lot easier to use :)
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Post by Weirdan »

[php_man]is_numeric[/php_man]:

Code: Select all

echo is_numeric($string) ? "numeric" : "some crap" ;
:lol:
User avatar
m3mn0n
PHP Evangelist
Posts: 3548
Joined: Tue Aug 13, 2002 3:35 pm
Location: Calgary, Canada

Post 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. :)
Post Reply