I want to check if a string is alpha-numeric and don't intend to use Regex
. I have am getting the correct answer but somehow the program is throwing an error stating undefined offset
. I have checked the array keys and seemingly they are fine.
$str="hello";
$arr=str_split($str);//convert a string to an array
$a=0;
$d=0;
for($i=0;$i<=count($arr);$i++)
{
if($arr[$i]>='a' && $arr[$i]<='z' || $arr[$i]>='A' && $arr[$i]<='Z')
{
$a=1;
}
elseif($arr[$i]>='0' && $arr[$i]<='9')
{
$d=1;
}
}
if($a==1&&$d==1)
{
echo "Alphanumeric";
}
else
{
echo "Not alphanumeric";
}
Array start at index zero, so the end ist i<count
for($i=0;$i<count($arr);$i++)
You should check out the ctype_alnum ( string $text )
; function.
$str="hello";
if(ctype_alnum($str))
{
echo "Alphanumeric";
}
else
{
echo "Not alphanumeric";
}
You should use either $i < count($arr)
or $i <= count($arr) -1
as arrays start at 0 and having just $i <= count($arr)
will result in an undefined offset
error message.