Answer the question
In order to leave comments, you need to log in
Is there a possibility of repeating one digit in this code?
There was a task to get 4 random numbers and that would not be repeated, I found a bunch of working examples on the Internet but decided to make my own
for ($i=0; $i <= 3 ; $i++ ) {
$randNumber[$i] = rand (1,100);
if ($randNumber[$i] == $randNumber[$i+1]) {
$randNumber [$i+1] = rand (1,100);
}
echo $randNumber [$i];
echo "<br>";
}
Answer the question
In order to leave comments, you need to log in
Of course, there is a possibility. As already mentioned, you cannot compare with the next empty value.
I think it's better to do this:
// Необходимое количество случайных чисел
$limit = 4;
// Максимальное значение случайного числа
$max = 100;
// Массив, в который складываются случайные числа
$numbers = [];
// Запускаем цикл
while(1) {
// Генерируем случайное число
$random = rand(1, $max);
// Проверяем, есть ли уже такое число в массиве-результате
if(!in_array($random, $numbers)) {
// Если такого числа нет, добавляем его в массив
$numbers[] = $random;
}
// Если уже набрали нужное количество чисел - выходим из цикла
if(count($numbers) == $limit) {
break;
}
}
var_dump($numbers);
there is. But as a matter of fact at you also it is not checked for uniqueness.
what does the if ($randNumber[$i] == $randNumber[$i+1]) { ??? compares to an empty value? To ensure uniqueness, you need to make a double loop: the main one for generating and the inner one for checking uniqueness.
for ($i=0; $i <= 3 ; $i++ ) { //$i=0;
$randNumber[$i] = rand (1,100); //Допустим 50
if ($randNumber[$i] == $randNumber[$i+1]) { //$randNumber[$i+1] == null для i=0
$randNumber [$i+1] = rand (1,100); //Допустим 50
}
echo $randNumber [$i]; //50
echo "<br>"; //<br>
}
There is. At least your validation won't work at all:
???? You don't have $randNumber[$i+1]. You've created $randNumber[$i] and you're checking with $randNumber[$i+1] that doesn't exist yet.
Suppose this is a typo and $randNumber[$i-1] was meant, but what about the previous element?
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question