2

I have the following code for selecting a random item out of an array each time a foreach loops through it's cycle.

<?php $variables = array('success', 'warning', 'info', 'danger'); ?>
   <?php foreach($os->list as $list): $var = 'success'; ?>
      <div class="progress-bar progress-bar-<?php echo $variables[array_rand($variables)]; ?>" style="width: <?php echo $list->metrics->visits; ?>%" title="<?php echo $list->os.' '.$list->version; ?>">
         <span class="sr-only"><?php echo $list->metrics->visits; ?>%</span>
       </div>
    <?php endforeach; ?>

My only problem is that one time it chooses success and then the next time it chooses success you then can't tell the difference in the data. I would be okay if it selected something like:

success, info, danger, success, danger, info

Just not:

success, info, info, danger, success, success

Where two items end up side by side.

Is there a way to do this or am I wasting my time?

UPDATE

I though this up but i'm not sure where to go with it:

<?php foreach($os->list as $list): $var = 'success'; ?>
   <?php
    if($var){

      $var1 = $var;

      $var = $variables[array_rand($variables)];

      if($var == $var1){


      }
     }
   ?>
   <div class="progress-bar progress-bar-<?php echo $var; ?>" style="width: <?php echo $list->metrics->visits; ?>%" title="<?php echo $list->os.' '.$list->version; ?>">
user3367639
  • 597
  • 3
  • 6
  • 20

2 Answers2

0

Just remove the currently selected array item and reorder the array How to Remove Array Element and Then Re-Index Array?

Community
  • 1
  • 1
Shuky Capon
  • 785
  • 5
  • 22
  • I don't have two arrays and can't hard code another array because I never know how many results I will have in the foreach statement. Actually put code in your answer that represents my code and I'll give it a shot. – user3367639 Mar 27 '14 at 07:17
0

Try something like this

$a = array('success', 'info', 'danger', 'warning');
$temp = array();

for ($i = 0; $i < 10; $i++) {
    $idx = array_rand($a);
    $result = $a[$idx];
    unset($a[$idx]);
    $a = array_merge($a, $temp);
    $temp = array();
    echo $result."\n";
    $temp[] = $result;
}

This moves last selected element out of array and moves it back in after next iteration selects random element.

frin
  • 4,474
  • 3
  • 31
  • 23