How to get random numbers on php, and so that every time the number of digits varies from 5 to 8, something like a captcha for example:

3 7 4 9 2 8 2 3 1 9 4 5 7 7 9 3 2 6 1 
  • It would be nice to start to independently google the answers to such questions. - Interface Unknown

3 answers 3

In general, there is nothing complicated here; you can use the standard array_rand () function into which you need to add an array of numbers and the number of digits to output.

  <?php $min = 5; $max = 8; $count_arr = rand($min, $max); $array = array(1,2,3,4,5,6,7,9); $random = array_rand($array,$count_arr); //$count_arr = количСство Ρ†ΠΈΡ„Ρ€ Π² массивС ΠΎΡ‚ 5 Π΄ΠΎ 8 shuffle($random); //ΠŸΠ΅Ρ€Π΅ΠΌΠ΅ΡˆΠ°Π΅ΠΌ массив ?> <?php foreach ( $random as $value ): ?> <b><?php echo $value." " ; ?></b> <?php endforeach ;?> 
     $leng = rand(5, 8); for ($i=0; $i < $leng; $i++) { echo rand(1, 9) . ' '; } 

    if I understand the ranges correctly

      This can be solved a little more elegantly:

       // МинимальноС пятизначноС число 10000, максимальноС Π²ΠΎΡΡŒΠΌΠΈΠ·Π½Π°Ρ‡Π½ΠΎΠ΅ β€” 99999999. $row = (string) rand(10000, 99999999); // Если количСство Π·Π½Π°ΠΊΠΎΠ² Ρ‚ΠΎΠΆΠ΅ задаётся динамичСски: $row = (string) rand( (integer) '1'.str_repeat('0', $min-1), (integer) str_repeat('9', $max) ); // Π”Π°Π»Π΅Π΅ для Ρ€Π°Π·Π±ΠΎΡ€Π°, ΠΏΠΎΠΌΠΈΠΌΠΎ substr() ΠΈΠ»ΠΈ mb_substr(), // ΠΌΠΎΠΆΠ½ΠΎ ΠΈΡΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚ΡŒ ΠΈ ΡΠ»Π΅Π΄ΡƒΡŽΡ‰ΠΈΠΉ синтаксис: // Π’Π°Ρ€ΠΈΠ°Π½Ρ‚ β„–1: $array = str_split($row, 1); // Π Π°Π·Π±ΠΈΠ²Π°Π΅ΠΌ строку $row Π½Π° элСмСнты Π² массивС $array // ΠΏΠΎ ΠΎΠ΄Π½ΠΎΠΌΡƒ символу Π² ΠΊΠ°ΠΆΠ΄ΠΎΠΌ ΠΈΠ· Π½ΠΈΡ… foreach ($array as $char) { // ΠŸΠΎΡ‚ΠΎΠΌ ΠΎΠ±Ρ…ΠΎΠ΄ΠΈΠΌ массив // И Π΄Π΅Π»Π°Π΅ΠΌ Ρ‡Ρ‚ΠΎ-Π½ΠΈΠ±ΡƒΠ΄ΡŒ с $char } // Π’Π°Ρ€ΠΈΠ°Π½Ρ‚ β„–2: for ($i = 0; $i < strlen($row); $i++) { $char = $row[$i]; // $row[$i] Π²ΠΎΠ·Π²Ρ€Π°Ρ‰Π°Π΅Ρ‚ ΠΎΠ΄ΠΈΠ½ символ строки, // Π³Π΄Π΅ $i β€” Π΅Π³ΠΎ порядковый Π½ΠΎΠΌΠ΅Ρ€. }