4

I'm a bit of a noob in PHP and I'm learning it right now. I'm making a website that displays 2 random pictures side by side. However at the moment with my current code, it means on some occasions you may get the same picture loaded twice. Here is my code:

<img src="images/
<?php
$pics = array('image1.jpg', 'image2.jpg', 'image3.jpg', 'image4.jpg');
echo $pics[array_rand($pics)];
?> " />

<img src="images/
<?php
$pics = array('image1.jpg', 'image2.jpg', 'image3.jpg', 'image4.jpg');
echo $pics[array_rand($pics)];
?> " />
CptnHedgey
  • 43
  • 2

3 Answers3

4

try the following

<?php
$pics = array('image1.jpg', 'image2.jpg', 'image3.jpg', 'image4.jpg');
$images = array_rand($pics, 2);
?>

<img src="images/<?php echo $pics[$images[0]]; ?>" />
<img src="images/<?php echo $pics[$images[1]]; ?>" />
Thiago França
  • 1,817
  • 1
  • 15
  • 20
  • Cheers! worked perfectly. So I guess that the '2' parameter in array_rand means it picks 2 from random. Then when you reference $images[0] and $images[1] it displays those two images it picked yes? – CptnHedgey Apr 15 '14 at 20:38
  • That's right! The second parameter is to tell how many results you want from randomization. – Thiago França Apr 15 '14 at 20:52
1

array_rand can return a list of random entries, instead of just one. http://www.php.net/manual/en/function.array-rand.php

<img src="images/
<?php
$pics = array('image1.jpg', 'image2.jpg', 'image3.jpg', 'image4.jpg');
$keys= array_rand($pics, 2);
echo $pics[$keys[0]];
?> " />

<img src="images/
<?php
echo $pics[$keys[1]];
?> " />
Barbara Laird
  • 12,599
  • 2
  • 44
  • 57
1

Determine the two random images first, and then handle the display part.

<?php
$pics = array('image1.jpg', 'image2.jpg', 'image3.jpg', 'image4.jpg');
$indexes = array_rand($pics, 2);
?>

<img src="images/
<?php
echo $pics[$indexes[0]];
?> " />

<img src="images/
<?php
echo $pics[$indexes[1]];
?> " />
Patrick Q
  • 6,373
  • 2
  • 25
  • 34