Reputation: 1
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
Reputation: 32232
Simply this will suffice:
$itemArray = array("item1.php", "item2.php", "item3.php");
shuffle($itemArray);
foreach ($itemArray as $item) {
include($item);
}
shuffle()
randomizes the array in-place, calling it multiple times is unnecessary and can cause items to be repeated or omitted.$itemArray
, but repeatedly including $itemArray[0]
for each iteration rather than the current item.Upvotes: 0
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
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