php -生成一个4位数

s3fp2yjn  于 2023-04-04  发布在  PHP
关注(0)|答案(1)|浏览(135)

对于验证码,下面的代码会生成一个5位数的数字。我希望它是4位数。我怎么做?

// generate random numbers
$sayilar = '';
for ($x = 15; $x <= 95; $x += 20) {
    $sayilar .= ($sayi = rand(0, 9));
    imagechar($image, rand(3, 5), $x, rand(2, 14), $sayi, $textcolor);
}
uajslkp6

uajslkp61#

你的循环定义是复杂的,因为你已经加载了很多不必要的逻辑。它会更清晰,更容易修改/维护:

$sayilar = '';
$lpad = 15;
$offset = 20;
for ($x = 0; $x < 4; ++$x) {
    $sayilar .= ($sayi = rand(0, 9));
    $xpos = $x * $offset + $lpad;
    imagechar($image, rand(3, 5), $xpos, rand(2, 14), $sayi, $textcolor);
}

相关问题