I have a string and I want to loop it so that I can check if every char is a letter or number.
$s = "rfewr545 345b";
for ($i=1; $i<=strlen($s); $i++){
if ($a[$i-1] == is a letter){
echo $a[$i-1]." is a letter";
} else {
echo $a[$i-1]." is a number";
}
}
How can I check if a char is a letter or a number?
To test if character is_numeric
, use:
is_numeric($a[$i-1])
As below:
$s = "rfewr545 345b";
for ($i = 0; $i < strlen($s); $i++){
$char = $s[$i];
if (is_numeric($char)) {
echo $char . ' is a number';
} else {
echo $char . ' is a letter';
}
}
With regular expressions you can try the following.
Test for a number
if (preg_match('/\d/', $char)) :
echo $char.' is a number';
endif;
Test for a "letter"
if (preg_match('/[a-zA-Z]/', $char)) :
echo $char.' is a letter';
endif;
The benefit of this approach is mainly from the "letter" test, which lets you efficiently define what constitutes as a "letter" character. In this example, the basic English alphabet is defined as a "letter".
See this:
http://php.net/manual/en/function.is-numeric.php
if(Is_numeric($char)) {
//Do stuff
}
else {
//Do other stuff
}
You can do by using is_numeric() function
if (is_numeric($a[$i-1])){
echo $a[$i-1]." is a number";
} else {
echo $a[$i-1]." is a letter";
}
php provide some nice function to checkout chars. Use the apt functions as conditions in if blocks.
visit:
PHP char functions
e.g. ctype_digit returns true if number is numeric.
You may use ctype_alpha to check for alphabetic character(s).
Similarly, you may use ctype_digit to check for numeric character(s).
is_numeric
— Finds whether a variable is a number or a numeric string
is_numeric()
example:
<?php
$tests = array(
"42",
0b10100111001,
"not numeric",
array(),
9.1
);
foreach ($tests as $element) {
if (is_numeric($element)) {
echo "'{$element}' is numeric", PHP_EOL;
} else {
echo "'{$element}' is NOT numeric", PHP_EOL;
}
}
?>
The above example will output:
'42' is numeric
'1337' is numeric
'not numeric' is NOT numeric
'Array' is NOT numeric
'9.1' is numeric
Where ctype_digit()
and is_numeric()
differ?
Example comparing strings with integers:
<?php
$numeric_string = '42';
$integer = 42;
ctype_digit($numeric_string); // true
ctype_digit($integer); // false (ASCII 42 is the * character)
is_numeric($numeric_string); // true
is_numeric($integer); // true
?>