I'm trying to validate user input by walking through the input and comparing to an array of acceptable characters using in_array(). But the results don't seem to be right.
For example:
$caps = range('A', 'Z');
$lc = range('a', 'z');
$nums = range('0', '9');
$space = array(' ');
$syms = array('.', '-', '"', "'", '(', ')');
$alnum = array_merge($caps, $lc, $nums);
$length = strlen($fieldvalue);
for ($i = 0; $i < $length; $i++)
{
if (!in_array($fieldvalue{$i}, $alnum))
{
echo 'error';
}
}
if I give it $fieldvalue = 'bob123#$%' I don't get an error. Shouldn't those non-alpha characters trigger my echo?
I tried specifying "strict" but that just caused the numbers to be rejected:
for ($i = 0; $i < $length; $i++)
{
if (!in_array($fieldvalue{$i}, $alnum, true))
{
echo 'error';
}
}
And give it $fieldvalue='bob1', I get the error message on the '1'. I suspect it has something to do with data types not matching. But both of these behaviors are puzzling to me.
Can anyone shed some light on this?
Btw - I'd use ctype_alnum() but in some cases I need to assemble custom character sets, including symbols or the space character.