2

The following is not working, why ?

    <?php
$divs = array('<li><span><i class="wo-themeicon"><img src="images/theme-icon/img-01.png" alt="img description"></i>Fire-resistant</span></li>',
              '<li><span><i class="wo-themeicon"><img src="images/theme-icon/img-02.png" alt="img description"></i>Moisture-resistant</span></li>',
              '<li><span><i class="wo-themeicon"><img src="images/theme-icon/img-03.png" alt="img description"></i>Impact-resistant</span></li>',
              '<li><span><i class="wo-themeicon"><img src="images/theme-icon/img-04.png" alt="img description"></i>Abuse-resistant</span></li>');

// Array with 2 random keys from $divs
$randKeys = array_rand($divs, 4);

                                    echo $divs[$randKeys[0]]; // First random div
                                    echo $divs[$randKeys[1]]; // Second random div
                                    echo $divs[$randKeys[2]]; // Third random div
                                    echo $divs[$randKeys[3]]; // Fourth random div
                                    ?>

It just displays the 4 array values, not displaying randomly. Results seems to be same always. I was expecting different sorting each time.

bre
  • 35
  • 4
  • You want 4 divs or 2 divs? – nice_dev Aug 18 '22 at 05:00
  • _What_ is not working? Blank page? Any errors? Why don't you just [shuffle](https://www.php.net/manual/en/function.shuffle.php) the `$divs` array? – brombeer Aug 18 '22 at 05:07
  • 2
    Yes `shuffle` is better. `array_rand` on an array with size 4 and picking all 4 elements results in same order each time. – nice_dev Aug 18 '22 at 05:10
  • 2
    [Some factual reading](https://stackoverflow.com/a/72973704/2943403) Most notably "_If multiple keys are returned, they will be returned in the order they were present in the original array._" That advice tuned to your 4 elements and 4 random selections: https://3v4l.org/MpuNn – mickmackusa Aug 18 '22 at 05:14

0 Answers0