tags:

views:

190

answers:

3
$images = array();
$images[0][0] = "boxes/blue.jpg";
$images[0][1] = "blah.html";
$images[1][0] = "boxes/green.jpg";
$images[1][1] = "blah.html";
$images[2][0] = "boxes/orange.jpg";
$images[2][1] = "blah.html";
$images[3][0] = "boxes/pink.jpg";
$images[3][1] = "blah.html";
$images[4][0] = "boxes/purple.jpg";
$images[4][1] = "blah.html";
$images[5][0] = "boxes/red.jpg";
$images[5][1] = "blah.html";
$images[6][0] = "boxes/yellow.jpg";
$images[6][1] = "blah.html";

$i = 0;


*echo "<a href='" . $images[0][1] . "'><img src='" . $images[0][0] . "' /></a>";

$boxes = array();
while($i<5)
{
 $rand = rand(0,(sizeof($images)-1));
 //echo $rand;
 $slice = array_splice($images, $rand);
 $boxes[$i] = $slice;
 $i++;
}*

I am trying to get a random image picker to choose from a list of images provided by the $images array. However, I am unable to fill the $boxes array with anything other than "Array". Can anyone tell me why? Any help is much appreciated

UPDATE

I am now using the code below and it breaks whenever it comes across an empty element. Unless i am very much mistaken, shouldn't splice patch up holes like that?

$rand = rand(0,(sizeof($images)));
array_splice($images, $rand);
$i = 0;
while($i<5)
{
 echo "<a href='" . $images[$i][1] . "'><img src='" . $images[$i][0] . "' /></a>";
 $i++;
}
A: 

array_splice() returns an array.

You can try something like this:

while($i<5)
{
        $rand = rand(0,(sizeof($images)-1));
        $boxes[$i] = $images[$rand];
        $i++;
}
Davide Gualano
+4  A: 

This might be a nicer way of doing it:

foreach (array_rand($images, 5) as $key) {
    $boxes[] = $images[$key];
}
Tom Haigh
+2  A: 

Slightly off topic, but wouldn't it be easier in this case (picking 5 items from a list of 6) just to pick one element and discard it from the original array, and then use the original? This will also ensure you do not get duplicates in the resultant array.

I realise that you may have more than 6 items in the original, and may want less than 5 from it, but I'm talking specifically about the example posted.

ZombieSheep
That's not a bad idea. That would definitely be easier.
Drew
So where's my upvote? ;-)
ZombieSheep