note 79819 deleted from function.is-numeric by felipe

From: Date: Sat, 15 Dec 2007 15:10:28 +0000
Subject: note 79819 deleted from function.is-numeric by felipe
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-133545@lists.php.net to get a copy of this message
Note Submitter: chris Reason: 1 ---- is_numeric() says "1/4" is not numeric so I made something that would say yes in this case. <?php function is_number_like ( $val ) { $val = preg_split( '#[ |/]#', $val ); $ret = true; foreach ( $val as $num ) { if ( !is_numeric( $num ) ) { $ret = false; break; } } return $ret; } //test this function - strings, integers, fractions, weird fractions, etc $numbers = array( '1', '1.12', 1.123, '1 1/2', '1/4', '0/0', 'not a number' ); foreach ( $numbers as $num ) { if ( is_number_like( $num ) ) { echo "'$num' is a number\n"; }else { echo "'$num' is NOT a number\n"; } } echo "\n"; ?> This outputs: '1' is a number '1.12' is a number '1.123' is a number '1 1/2' is a number '1/4' is a number '0/0' is a number 'not a number' is NOT a number You'll notice that 0/0 is still recognized as a number although it's technically NOT a number, this is trivial to fix if you need this capability... I didn't... All I needed to know was whether it looked like a number =)

« previous php.notes (#133545) next »