Reputation: 633
I am creating a 'Tips' section which changes on refresh. I had only text earlier but now there is an image associate with each tip.
I am randomising both arrays which is wrong. How do I link them?
It should be 'Tip 1' => '1.jpg', 'Tip 2' => '2.jpg', 'Tip 3' => '3.jpg'
Any suggestions would be highly appreciated.
<?php
function array_random($arr, $num = 1) {
shuffle($arr);
$r = array();
for ($i = 0; $i < $num; $i++) {
$r[] = $arr[$i];
}
return $num == 1 ? $r[0] : $r;
}
$a = array(
"Tip 1",
"Tip 2",
"Tip 3");
$img = array(
"1.jpg",
"2.jpg",
"3.jpg");
?>
Thank you.
Upvotes: 0
Views: 41
Reputation: 3461
Simply, join them in one array
$tips = array();
$tips[] = array("Tip" => "Tip text 1", "Image" => "Tip Image 1");
$tips[] = array("Tip" => "Tip text 2", "Image" => "Tip Image 2");
shuffle($tips);
echo $tips[0]['Tip']; // tip text
echo $tips[0]['Image']; // tip image
Upvotes: 2
Reputation: 17586
try this
$new = array_combine($a,$img);
shuffle($a);
echo $tip = $a[0];
echo $image = $new[$a[0]];
Upvotes: 1