Support

Account

Home Forums General Issues How to Randomize This? Reply To: How to Randomize This?

  • 
    $rows = get_field('books', 34);
    if (!empty($rows)) {
      $max_to_show = 2;
      $row_count = count($rows);
      $shown_rows = array();
      $i = 0;
      for ($loop=0; $loop<$max_to_show; $loop++) {
        // show 2 images
        if ($row_count > $max_to_show) {
          // only randomize if more than max to show
          $i = rand(0, $row_count - 1);
          while (in_array($i, $shown_rows)) {
            // make sure it's not duplicate
            $i = rand(0, $row_count - 1);
          }
          
        } // end if > max to show
          
        // ********************************
        // output row $i here
        // ********************************
          
        $shown_rows[] = $i;
        
        if ($row_count <= $max_to_show) {
          // increment value in cases rows is <= max to show
          $i++;
          if ($i >= $row_count) {
            // make sure that we don't exceed number of rows that exist
            break;
          }
        }
        
      } // end for
    } // end if rows