0

i have an array and its data are displayed in a grid using a foreach loop. the index of the foreach is used as part of url for each entry in the grid.

$i=0;   
foreach ($array as $grid) {
 $name = $grid->name;
 $address = $grid->address;
 echo '<li> <a href="javascript:myclick('.$i.');" title="">' . $name . '</a> </li>';
 $i++;
}

i'd like to display the array in random order so i used shuffle(); but the index gets destroyed and the links break. i have been looking around for 2 days and tried many different kinds of functions that were supposed to keep the index untouched but with no luck. any help would be much appreciated.

2 Answers 2

3

safer shuffle the real keys of an array

$keys = array_keys($arr);
shuffle($keys);
foreach($keys as $i) {
Sign up to request clarification or add additional context in comments.

Comments

0

Shuffle the index instead:

$index = range(0, sizeof($array));
shuffle($index);
foreach ($index as $i) {
    // $array[$i], $i 
}

You got the idea.

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.