how to shuffle a php array but keep the index in foreach

1.7k Views Asked by At

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

There are 2 best solutions below

0
On BEST ANSWER

safer shuffle the real keys of an array

$keys = array_keys($arr);
shuffle($keys);
foreach($keys as $i) {
0
On

Shuffle the index instead:

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

You got the idea.