我知道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"
怎么了?
看起来你有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
。true = true,也就是true