Rewind Rewind - 1 year ago 85
PHP Question

Php Arrays - Number strings indexes

I know myarray[1] and myarray["1"] point to the same thing. But even with that knowledge I am still having a bit of trouble.

I have this:

$KEYS = ["1", "2", "3", "4", "5", "6", "7", "8", "9",
"A", "B", "C", "D", "E", "F", "G", "H", "J",
"K", "L", "M", "N", "P", "R", "S", "T",
"U", "V", "W", "X", "Y", "Z"];

$KEYS_LENGTH = count($KEYS);

$KEYS_INVERSE = array();
for ($i = 0; $i < $KEYS_LENGTH; $i++) {
$KEYS_INVERSE[$KEYS[$i]] = $i;

Then later on I do this:

$str = "A21"; // Some random string built with the letters of $KEYS
$len = strlen($str);
if ($KEYS_INVERSE[$str[$i]] == "undefined") return false; // AN ERROR - This is the problem line
// Carry on happily doing stuff

Everything goes great. When $str[$i] is "A" that is fine. Even when $str[$i] is "2" that is fine. But when $str[$i] is "1" it triggers that 'return false;' believing $KEYS_INVERSE[$str[$i]] == "undefined".

What is going wrong?

Answer Source

Looks like you have javascript background. )

First of all, the first section of the code can be reduced to this:

$KEYS = ["1", "2", "3", "4", "5", "6", "7", "8", "9",
         "A", "B", "C", "D", "E", "F", "G", "H", "J",
         "K", "L", "M", "N", "P", "R", "S", "T",
         "U", "V", "W", "X", "Y", "Z"];

$keys_inverse = array_flip($KEYS); // Is it really needed?..

But is there really a point in that? Since you're collecting keys if a sequential array, you'll get this as result:

[0, 1, 2, 3, 4, 5 ...];

In fact, any sequential array will return the same result here, as long as number of elements is preserved.

Since you need to validate that the random string contains only characters from $KEYS array, you need to compare each character of the string with the values of the $KEYS array:

$str = 'A21';

$strchars = str_split($str);
// This will create array ['A', '2', '1'];

if (array_diff($strchars, $KEYS)) { // if $strchars contains values that are not presented in $KEYS array, array_diff function will return those values in form of array, which evaluates to true
    // The string contains characters that are not presented in the $KEYS array

The reason for this expression 1 == "undefined" is because PHP evaluates 1 to true and non-empty string "undefined" is also evaluated to true. So, true equals true, which is true.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download