fabrizio.rocca fabrizio.rocca - 2 months ago 14
PHP Question

How to display all array values once and in random order?

I need a PHP script for my website in order to pick (all) values from an array and display them randomly.

Every value must be shown only once.

This is the code I've written so far, the problem is that the values are not taken once.

<?php
$one = 'SITE 1<br><br>';
$two = 'SITE 2<br><br>';
$three = 'SITE 3<br><br>';
$four = 'SITE 4<br><br>';
$five = 'SITE 5<br><br>';

$array = array($one, $two, $three, $four, $five);
for ($i=0; $i<5; $i++) {
echo $array[rand(0, count($array) - 1)] . "\n";
}
?>


You can test this code directly here: https://www.fabriziorocca.it/test/phprandom.php

Answer

You can use shuffle:

<?php
$one = 'SITE 1<br><br>';
$two = 'SITE 2<br><br>';
$three = 'SITE 3<br><br>';
$four = 'SITE 4<br><br>';
$five = 'SITE 5<br><br>';

$array = array($one, $two, $three, $four, $five);
shuffle($array);
foreach($array as $item) {
    echo $item . "\n";
}
?>
Comments