Reputation: 51
I need to specify whether the type of string starts with either 3 digits, 3 letters, or a combination. The string the user types.
The code i have works for letters and numbers, but not for the combinations. What should I do?
$type = substr($value, 0, 3);
if(is_numeric($type)){
echo 'starts with 3 digits';
}elseif(is_string($type)){
echo 'starts with 3 alphabetic characters';
}else{
echo 'undefined type?';
}
Upvotes: 1
Views: 55
Reputation: 47894
Your function calls might return unintended results. I recommend ctype_
calls for reliability:
$type = substr($value, 0, 3);
if(ctype_digit($type)){
echo 'starts with 3 digits';
}elseif(ctype_alpha($type)){
echo 'starts with 3 alphabetic characters';
}else{
echo 'undefined type?';
}
p.s. If you want to check if the substring is a combination of letters and numbers, you can can ctype_alnum()
.
Upvotes: 3