You can use is_numeric
to check for a numeric field, it doesn't matter whether the variable is a string or not. See example here.
Then you can simply pad using str_pad()
if(!is_numeric($test))
echo $test . ' is not a number!';
else
echo str_pad($test, 5, 0, STR_PAD_LEFT);
Edit: as flixer pointed out, is_numeric()
won't actually do what you specifically asked (to check that a string contains only digits, i.e. no periods, commas, dashes etc which would be considered to "be a number"). In this case, use ctype_digit()
instead:
$test_number = '123.4';
$test_number2 = '12345';
echo ctype_digit($test_number) ? $test_number . ' is only digits' : $test_number . ' is not only digits';
echo ctype_digit($test_number2) ? $test_number2 . ' is only digits' : $test_number2 . ' is not only digits';
// output:
// 123.4 is not only digits
// 12345 is only digits
The key here is to avoid regex when you have better tools to do the job.
To add a little to this, ctype_digit()
might return false when you pass in an integer variable: (example from PHP manual)
ctype_digit( '42' ); // true
ctype_digit( 42 ); // false - ASCII 42 is the * symbol
This can be OK, depending on the situation you're using this in. In your case you're validating a $_GET
variable, which is always going to be a string so it won't affect you.
Docs:
str_pad()
: http://php.net/str_padctype_digit()
: http://www.php.net/manual/en/function.ctype-digit.php
OP Here, this is it all together. Works like a charm...
if (ctype_digit($getuname) == true) {
$getuname = str_pad($getuname, 5, 0, STR_PAD_LEFT);
}