dongshang1979 2016-10-06 18:42
浏览 45
已采纳

Php Arrays - 数字字符串索引[重复]

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

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?

</div>
  • 写回答

1条回答 默认 最新

  • duanang58939 2016-10-06 18:53
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 数学建模,尽量用matlab回答,论文格式
  • ¥15 昨天挂载了一下u盘,然后拔了
  • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题
  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能