Php Arrays - 数字字符串索引

时间:2016-10-06 18:43:00

标签: php arrays indexing

我知道myarray [1]和myarray [“1”]指向同一件事。但即使有了这些知识,我仍然会遇到一些麻烦。

我有这个:

$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;
}

然后我会这样做:

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

一切都很好。当$ str [$ i]是“A”时,没问题。即使$ str [$ i]为“2”也没关系。但是当$ str [$ i]为“1”时,它会触发“返回false”;相信$ KEYS_INVERSE [$ str [$ i]] ==“undefined”。

出了什么问题?

1 个答案:

答案 0 :(得分:1)

看起来你有javascript背景。 )

首先,代码的第一部分可以简化为:

$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?..

但是真的有一点吗?由于您在顺序数组中收集密钥,因此您将获得此结果:

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

事实上,任何顺序数组将在此处返回相同的结果,只要保留元素数量。

由于您需要验证随机字符串是否仅包含$KEYS数组中的字符,您需要将字符串的每个字符与$KEYS数组的值进行比较:

$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
}

此表达式1 == "undefined"的原因是因为PHP将1评估为true,而非空字符串"undefined"也评估为true。所以,真实等于真,这是真的。