user2777790
user2777790

Reputation: 1

Randomize Array then retrieve in foreach loop

I'm trying to output the values of an array randomly, so there is no order to the way they are displayed. It works, not as expected.

They still display in the same order they are listed in the array, so I must be missing something..

    $itemArray = array("item1.php", "item2.php", "item3.php");
        shuffle($itemArray); 

        foreach ($itemArray as $item) {
                    shuffle($itemArray); 

                    include($itemArray[0]);

                }

Should I be using rand_array instead?

Upvotes: 0

Views: 1454

Answers (3)

Sammitch
Sammitch

Reputation: 32232

Simply this will suffice:

$itemArray = array("item1.php", "item2.php", "item3.php");
shuffle($itemArray); 

foreach ($itemArray as $item) {
    include($item);
}
  1. shuffle() randomizes the array in-place, calling it multiple times is unnecessary and can cause items to be repeated or omitted.
  2. You are looping through the elements in $itemArray, but repeatedly including $itemArray[0] for each iteration rather than the current item.

Upvotes: 0

Ed Capetti
Ed Capetti

Reputation: 339

There is no need for shuffle it again inside your foreach.

$itemArray = array("item1.php", "item2.php", "item3.php");
shuffle($itemArray); 

foreach ($itemArray as $item) {
     include($item);
}

Read the documentation for the correct use of foreach: http://www.php.net/manual/en/control-structures.foreach.php

Upvotes: 0

Paolo Bergantino
Paolo Bergantino

Reputation: 488394

Inside your foreach the variable $item contains the current item, so it would look like:

foreach($itemArray as $item) {
    include($item);
}

Not sure what the reasoning is for including files in a random order, though...

Upvotes: 2

Related Questions