ctype_digit()
Cara termudah dan tercepat untuk mengecek seluruh karakter string adalah nomor ialah dengan menggunakan ctype_digit ( )
$var = '1337';
if(ctype_digit($var)){
echo 'This string contains only digits';
}
preg_match()
Cara lain untuk mengecek apakah kalimat tersebut hanya mengandung angka adalah dengan menggunaakan preg_match(). preg_match() akan mencari suatu pola dan mengembalikan jumlah pola yang sesuai. Dalam contoh berikut akan digunakan 3 macam pola yang sebetulya memiliki makna yang sama. String harus mengandung hanya angka.
if(preg_match('/^\d+$/',$var)){
echo 'This string contains only digits';
}
if(preg_match("/^[0-9]+$/",$var)){
echo 'This string contains only digits';
}
if(preg_match("/^[[:digit:]]+$/",$var)){
echo 'This string contains only digits';
}
[0-9] dan [:digit:] adalah character classes that means we are only looking for numbers in the string. In other words,[0-9] is a pattern that covers all digits:0 1 2 3 4 5 6 7 8 9. \d is a shorthand of [0-9] and [:digit:].
Jangan gunakan is_numeric() atau is_int()
is_numeric() and is_int() are not really meant to check if a string contains only numbers.
is_numeric() will return TRUE if a string is a numeric string but don't forget a numeric string is not necessarily an integer. A numeric string can also be a decimal number or a negative number. That is why you would not want to use is_numeric() if you are only looking for positive integers (0 1 2 3 4 5 6 7 8 9).
$tests = array('1.3', '-2', '1e3');
foreach($tests as $element){
if(is_numeric($element)) {
echo $element.' is numeric
';
}
}
This script will output:
1.3 is numeric
1e3 is numeric
-2 is numeric
is_int() will return TRUE if the type of a variable is integer. That means it will return TRUE for integers that are positive or negative numbers.
if(is_int(-1)) {
echo 'This number is an integer';
}
is_int() checks the type of a variable (a variable can be a boolean, an integer, a string, an array or plenty other things). As you may want to check if the values sent through a form contains only numbers, don't forget that everything from $_POST is considered as a string. So doing something like is_int($_POST['var']) will always return FALSE, even if this string contains numbers only.
$var = '3';
if(!is_int($var)){
echo '$var is a '.gettype($var).', it is not an integer';
}
This script will output:
3 is a string, it is not an integer
Komentar
Posting Komentar