0

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?

3 Answers 3

2

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...

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

Comments

0

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

Comments

0

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.

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.