Reputation: 83
please help I need create some array random from this case:
foreach (range(1,3) as $number) {
$lala1= "\"img$number\",";
$lala2 = array("$lala1");
echo $lala2[array_rand($lala2)];
}
Is give me this result:
"img1","img2","img3",
but I need the result to show random like this:
img1 (with random img1,img2, or img3)
Thank you
Upvotes: 2
Views: 62
Reputation: 9947
You are making a one element array ($lala2
) and "randomizing" it on each iteration, which is why you get all 3 elements printed out.
What you need to do is add a new element on each iteration, and only then use array_rand()
to pick a random element out of the resulting array:
<?php
$imgs = []; // define the array where you'll store the elements
foreach (range(1,3) as $number) {
$lala1 = "\"img$number\",";
$imgs[] = $lala1; // add the new element to the array
}
echo $imgs[array_rand($imgs)]; // pick a random value
Upvotes: 3
Reputation: 781706
You need to add to the array each time through the loop, not replace it, and then use array_rand()
after the loop.
$lala2 = array();
foreach (range(1, 3) as $number) {
$lala1 = "\"$img$number\",";
$lala2[] = $lala1;
}
echo $lala2[array_rand($lala2)];
Upvotes: 1