字符串中的数组语法:未初始化的字符串偏移错误 [英] Array syntax in string: Uninitialized string offset error

查看:49
本文介绍了字符串中的数组语法:未初始化的字符串偏移错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在以下在线发布的代码中得到了一个未初始化的字符串偏移量:

I'm getting an unitialized string offset in the following code that was posted online:

function generateKey() {
    $length = 15;
    $characters = '0123456789abcdefghijklmnopqrstuvwxyz';
    $string = '';
    for ($p = 0; $p < $length; $p++) {
        $string .= $characters[mt_rand(0, strlen($characters))];
    }
    return $string;
}

是不是因为 $characters[] 被应用于字符串?我不完全明白错误意味着什么,但我如何才能达到同样的效果并解决这个问题(它现在工作正常,只是抛出一个错误)?

Is it because of $characters[] being applied to a string? I don't fully get what the error means, but how could I achieve the same effect and get around that (it's working fine right now, just throwing an error)?

推荐答案

基本上已经回答了,但我建议

Basically what has been already answered, but I suggest

  • 只执行一次 strlen() 操作并将最大随机数存储到一个变量中,
  • 初始化 $string 缓冲区并写入其中,而不是进行连续的连接,
  • 减少计数器 $p 以便从后到前工作.
  • do the strlen() operation only once and store the maximum random number into a variable,
  • initialize the $string buffer and write into it instead of an ongoing concatenation,
  • decrease the counter $p so to work from back to front.

演示,代码:

function generateKey() {
    $length = 15;
    $characters = '0123456789abcdefghijklmnopqrstuvwxyz';
    $maxrnd = strlen($characters)-1;
    $string = str_repeat('0', $length);
    for ($p = $length; $p--;) {
        $string[$p] = $characters[mt_rand(0, $maxrnd)];
    }
    return $string;
}

这篇关于字符串中的数组语法:未初始化的字符串偏移错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆