Phoenixy
Phoenixy

Reputation: 114

How to get same number of item from two random arrays?

The question may sounds a bit weird, but I'll try to explain what I want to achieve. I have two arrays:

$combined_alt_blur = array($bg['pic_blur'], $bg['pic_blur2'], $bg['pic_blur3'], $bg['pic_blur4'], $bg['pic_blur5']);
$combined_alt_normal = array($bg['pic_normal'], $bg['pic_normal2'], $bg['pic_normal3'], $bg['pic_normal4'], $bg['pic_normal5']);

Then I show them on the website:

<div class="fullscreen_blur" style="background-image: url('/medias/<?php print $combined_alt_blur[array_rand($combined_alt_blur)]; ?>.jpg');"></div>
<div class="fullscreen"  style="background-image: url('/medias/<?php print $combined_alt_normal[array_rand($combined_alt_normal)]; ?>.png');"></div>

But there's a huge problem with this one. If the random from the first array chooses the 3rd item (pic_blur3), then it must choose the 3rd item from the second array as well (pic_normal3). How can I achieve this?

With the current code it's just two seperate random arrays.

Upvotes: 0

Views: 27

Answers (2)

HTMHell
HTMHell

Reputation: 6016

If both arrays has the same size of cells, you can just do:

$index = array_rand($combined_alt_blur);
print $combined_alt_blur[$index];
print $combined_alt_normal[$index];

Otherwise you can assign maybe a default value:

print isset($combined_alt_normal[$index]) ? $combined_alt_normal[$index] : "default";

Upvotes: 3

baao
baao

Reputation: 73251

Create a random number and use it as an index for both

$index = rand(0, count($combined_alt_blur) - 1);
$combined_alt_normal[$index];

Upvotes: 1

Related Questions