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 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 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 β Π΅Π³ΠΎ ΠΏΠΎΡΡΠ΄ΠΊΠΎΠ²ΡΠΉ Π½ΠΎΠΌΠ΅Ρ. } Source: https://ru.stackoverflow.com/questions/442329/
All Articles