how to select 3 fruit from 4 fruit in sequence and alternately?
how to select 3 fruit from 4 fruit in sequence and alternately?
for example i have this sequence : orange, banana, apple and raspberry. i want to show 3 data in sequence and alternately like this :
etc
note :
the amount of data i want to display changes
i try using array_push and array_pop but i stuck when i want to random it. here my code :
array_push
array_pop
<?php
$stack = array("orange", "banana");
array_push($stack, "apple", "raspberry");
array_pop($stack);
print_r($stack);
?>
can anyone fix my code?
@jeroen would not using shuffle would just random rather than sequentially?
– Daniel Alfianto
Jul 2 at 8:09
if you want to keep your sequence, just pick a random number between 0 and the length of your array and pick your 3 elements from this index (you will have to check to restart from the begining if you reach the end of the array)
– ᴄʀᴏᴢᴇᴛ
Jul 2 at 8:09
2 Answers
2
you can use this code :
function pickElementsFromArray($array, $countToPick)
{
$start = rand(0, count($array)-1);
$picked = 0;
$elements = ;
while ($picked < $countToPick) {
$elements = $array[$start];
$start++;
if ($start >= count($array)) {
$start = 0;
}
$picked++;
}
return $elements;
}
$array = ["orange", "banana", "apple", "raspberry"];
$elemsToPick = 3;
$elements = pickElementsFromArray($array, $elemsToPick);
This functions starts the picking from a random position and from there it picks n elements. if the end of the array is reached, it restarts from the begining
You can try this
$fruits=array('orange', 'banana', 'apple', 'raspberry');
function pick($count,$fruits){
$counter=0;
for ($i = 0; $i <=count($fruits)+1 ; $i++) {
if ($i>=$count) {
if ($counter<=2) {
if (array_key_exists($i, $fruits)) {
echo $fruits[$i];
echo '<br>';
$counter++;
}
else{
$counter++;
echo $fruits[0];
}
}
}
}
}
echo pick(0,$fruits);
echo '<br>';
echo pick(1,$fruits);
echo '<br>';
echo pick(2,$fruits);
OUTPUT:
orange
banana
apple
banana
apple
raspberry
apple
raspberry
orange
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
php.net/manual/en/function.shuffle.php
– jeroen
Jul 2 at 8:06