+ 1
What is happening here?
Hello, Can someone help to figure out what is happening here? I put some comments in some of the lines. Tx for the help. <?php $card = array(); for ($row = 1; $row < 8; ++$row){ $card[$row] = array(); $deck = range(0,9); // make a array with 0 to 9 for ($kolom = 1; $kolom < 8; ++$kolom){ $index = mt_rand(0,count($deck) - 1);// is this a random number between 0 and 10 while the -1 removes the chosen one? $number = $deck[$index]; why is it like this and why not only the index number? $card[$row][] = $row . $number; //row + number to get random number is that correct? unset($deck[$index]); //empty the var $deck = array_values($deck); //how is it possible to do thit while the var has been unset? } } ?> Greetings Moos
5 odpowiedzi
+ 7
Updated to show output...
https://code.sololearn.com/wM2fcvu1h2e0
+ 6
While it doesn't generate an error, I believe your line:
$card[$row][] = $row . $number;
is incorrect. I think the [] should be [$kolom]. Your $index assignment gets a random value of the remaining elements in $deck. $number gets assigned the value in the selected element. $card[$row][$kolom] would store a two digit number in that array position so, if $index was 5, $number would be 5 and 15 would be stored. The next loop, if $index was 5 once more, $number would be 6 and 16 would be stored. Your unset statement removes that array element without touching the others so the first loop would remove the 5 and the second the 6 in my example above. The $deck assignment is not needed as it only changes $deck to what it already was to begin with.
$card would end up with a 7x7 set of numbers such as:
15 16 13 19 10 12 14
29 20 24 28 21 22 26
33 39 37 32 30 35 34
40 47 42 49 47 46 45
57 55 56 52 58 51 50
63 69 68 62 60 65 66
79 72 70 73 78 76 74
+ 5
Added better comments to my code to reflect what is happening.
+ 4
Okay. I was wrong. The $deck assignment is needed to close the gaps in the array. Without that line you still have an element there that can't be used.
+ 1
Thank you so much. This helpt me a lot. Your right about to add $kolom in $card[$row][]. Thanks for the help.