1

I'm building an advent calendar in PHP 7 and want to show dates 1 - 24 in a random order.

I've got a jquery plugin which can randomise my div elements, but it's not very good, and I want to know how to do it in PHP.

My code to output the dates looks (in simplified terms) like this:

for ($d = 1; $d <= 24; $d++) {
    echo $d;
}

My plan was to instead use rand(1, 24) then store any numbers that had been generated in an array, e.g.

$date = rand(1, 24);
$used_dates[] = $date;

Then check $used_dates when picking a new date, e.g.

$unique_date = false;
while (!$unique_date) {
    $date = rand(1, 24);
    if (!in_array($date, $used_dates)) {
       $used_dates[] = $date;
       $unique_date = true;
    }
}

This seems inefficient though. Are there better ways?

3 Answers 3

10

In your case, you need create range array of numbers, and then simply shuffle them

$days = range(1,24);
shuffle($days);

Thats all

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

Comments

3

You can use shuffle() method.

Shuffle() take an array and order rows randomly.

$array = array("a", "b", "c");
shuffle($array);
// OUTPUT is random

Comments

3
$numbers = range(1, 24);
shuffle($numbers);

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.