Solved

# php check for digits

Posted on 2012-04-07
260 Views
hi ,

I need to be able to check the first 9 digits of a string are numbers, how would i do this?

pass
123456783x
359372910flasd
fail
3k33j52l4
asd3asd323
asd2345343213

thanks
0
Question by:MK15
• 2

LVL 82

Assisted Solution

Dave Baldwin earned 250 total points
ID: 37819818
Use 'ctype_digit' and 'substr'.

``````<?php
\$strings = array('pass', '123456783x', '359372910flasd','fail','asd2345343213');
foreach (\$strings as \$testcase) {
if (ctype_digit(substr(\$testcase, 0, 9))) {
echo "The string \$testcase consists of all digits.\n";
} else {
echo "The string \$testcase does not consist of all digits.\n";
}
}
?>
``````
0

LVL 82

Expert Comment

ID: 37819836
This is a better version:

``````<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<html>
<title>PHP Digits</title>
<body>
<h1>PHP Digits</h1>
<?php
\$strings = array('pass', '123456783x', '359372910flasd','fail','asd2345343213');
foreach (\$strings as \$testcase) {
if (ctype_digit(substr(\$testcase, 0, 9))) {
} else {
echo "Fail - The string '\$testcase' does Not start with 9  digits.<br>\r\n";
}
}
?>

</body>
</html>
``````
0

LVL 18

Accepted Solution

Andrej Pirman earned 250 total points
ID: 37819842
``````\$string = "4534563436nmrer";
\$first_part = substr(\$string, 0, 9);
if (intval(\$first_part)==\$first_part) {
echo "First 9 chars are numerical";
} else {
echo "Not numerical";
}
``````
0

Author Comment

ID: 37821310
cheers guys they both did the trick
0

## Featured Post

### Suggested Solutions

Introduction HTML checkboxes provide the perfect way for a web developer to receive client input when the client's options might be none, one or many.  But the PHP code for processing the checkboxes can be confusing at first.  What if a checkbox is…
Developers of all skill levels should learn to use current best practices when developing websites. However many developers, new and old, fall into the trap of using deprecated features because this is what so many tutorials and books tell them to u…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.