2

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

2 Answers 2

3

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

Demo

Sign up to request clarification or add additional context in comments.

1 Comment

That looks exactly like what I was typing up. Beat me to it ;)
1

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)];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.