I have the following code:
<?php
foreach($bb['slides'] as $b):
$url = "domain.com/" . $b->image . ";
echo($url);
endforeach;
?>
The output is as follows: domain.com/image1.jpg domain.com/image2.jpg domain.com/image3.jpg
I am trying to randomize the order of the output. Before the foreach statement I tried to shuffle the array using shuffle($bb); but that did not work. Any help is appreciated.
Answer: Use the PHP shuffle() function You can use the PHP shuffle() function to randomly shuffle the order of the elements or values in an array. The shuffle() function returns FALSE on failure.
The shuffle() Function is a builtin function in PHP and is used to shuffle or randomize the order of the elements in an array. This function assigns new keys for the elements in the array. It will also remove any existing keys, rather than just reordering the keys and assigns numeric keys starting from zero.
Write the function shuffle(array) that shuffles (randomly reorders) elements of the array. Multiple runs of shuffle may lead to different orders of elements. For instance: let arr = [1, 2, 3]; shuffle(arr); // arr = [3, 2, 1] shuffle(arr); // arr = [2, 1, 3] shuffle(arr); // arr = [3, 1, 2] // ...
Python Random shuffle() Method The shuffle() method takes a sequence, like a list, and reorganize the order of the items. Note: This method changes the original list, it does not return a new list.
As $bb is an array of arrays, shuffle() won't randomise the sub-array, try shuffle
on the nested array as follows:
shuffle($bb['slides']);
You probably shuffled the outer $bb array, when you should have done:
shuffle($bb['slides']);
foreach($bb['slides'] as $b):
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With