Search code examples
phprandomnumbers

php - generate a 4 digit number


For the captcha, the code below generates a 5-digit number. I want it to be 4 digits. how can I do it.

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

Solution

  • Your loop definition is convoluted since you've loaded a lot of unnecessary logic into it. It would be more clear and easier to modify/maintain as:

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