Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 274
  • Last Modified:

php check for digits

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
MK15
Asked:
MK15
  • 2
2 Solutions
 
Dave BaldwinFixer of ProblemsCommented:
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";
    }
}
?>

Open in new window

0
 
Dave BaldwinFixer of ProblemsCommented:
This is a better version:

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

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

</body>
</html>

Open in new window

0
 
Andrej PirmanCommented:
$string = "4534563436nmrer";
$first_part = substr($string, 0, 9);
if (intval($first_part)==$first_part) { 
   echo "First 9 chars are numerical"; 
} else {
   echo "Not numerical";
}

Open in new window

0
 
MK15Author Commented:
cheers guys they both did the trick
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now