Help with 2D array creation

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
laurieloo89
Forum Newbie
Posts: 1
Joined: Tue Feb 15, 2011 5:38 pm

Help with 2D array creation

Post by laurieloo89 »

Evening all:)

I'm new to this forum, so apologies if this problem has been previously covered or if I should be posting this in a different topic.

Just a quick question.
I'm needing to create a 2D array(4 rows and 4 columns) containing 16 random unique numbers between 1 and 60(inclusive). I'm still in the middle of learning PHP so I'm having a small problem coding.
I've created my 2D array already, but I'm having trouble with the unique numbers. Although I have the number unique to each row/column, I can't seem to get my head around being able to get each number unique to the overall 2D array.

Any help/advice would be much appreciated!
User avatar
AbraCadaver
DevNet Master
Posts: 2572
Joined: Mon Feb 24, 2003 10:12 am
Location: The Republic of Texas
Contact:

Re: Help with 2D array creation

Post by AbraCadaver »

Code please. Each time you generate a random put it in a 1d tracking array. When you generate the number check in the tracking array to make sure it hasn't been used: in_array()
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
User avatar
Jonah Bron
DevNet Master
Posts: 2764
Joined: Thu Mar 15, 2007 6:28 pm
Location: Redding, California

Re: Help with 2D array creation

Post by Jonah Bron »

I feel like coding :)

Code: Select all

$rands = array();                            // create array to hold random numbers
for ($i = 0; $i < 16; $i++) {                // loop 16 times (4x4)
    do {                                     // use do...while to ensure uniqueness
        $num = rand(0, 60);                  // get a random number
    } while (in_array($num, $rands, true));  // make sure it's not already used
    $rands[] = $num;                         // add to list
}

$final = array();                            // create final 2d array
for ($i = 0; $i < 4; $i++) {                 // iterate 4 times for first dimension
    $temp1 = array();                        // create second dimension array
    for ($j = 0; $j < 4; $j++) {             // iterate 4 times for second dimension
        $temp1[] = array_pop($rands);        // grab number from list
    }
    $final[] = $temp1;                       // put 2nd dimension into first dimension
}
Post Reply