Last active
December 22, 2015 08:08
-
-
Save vendion/6442742 to your computer and use it in GitHub Desktop.
Quick example code to take an array of times and randomly grab ten elements from that array. If the source array has less than ten elements, grab all of the elements in a random order.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// set up array with slides | |
$slides = array(1, 2, 3, 4, 5); | |
//$slides = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); | |
//$slides = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15); | |
// get ten random array elements to display | |
$length = count($slides); | |
$maxLength = 10; | |
if ($length < 10) { | |
$maxLength = $length; | |
} | |
echo "Array length: $length and Max length: $maxLength\n"; | |
$length--; | |
$randSlides = array(); // create empty array that hold the elements | |
// to disply | |
for ($i = 0; $i < $maxLength; $i++) { | |
$n = rand(0, $length); | |
if (empty($n)) { | |
$n = 0; | |
} | |
if (! in_array($n, $randSlides)) { | |
array_push($randSlides, $n); | |
} else { | |
--$i; // decrement $i causing the loop to rerun this | |
// illiteration | |
continue; | |
} | |
} | |
echo 'Number of elements in $randSlides: ' . count($randSlides) . "\n"; | |
// Display the randomly selected slides | |
foreach($randSlides as $slide) { | |
echo $slides[$slide] . ' '; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment