Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shuffle an array in PHP

Tags:

php

shuffle

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.

like image 767
user663561 Avatar asked Mar 17 '11 02:03

user663561


People also ask

How do I shuffle an array in PHP?

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.

What does shuffle do in PHP?

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.

How do you shuffle an array in HTML?

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] // ...

What is shuffle () in Python?

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.


2 Answers

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']);
like image 134
Meberem Avatar answered Sep 20 '22 22:09

Meberem


You probably shuffled the outer $bb array, when you should have done:

shuffle($bb['slides']);
foreach($bb['slides'] as $b):
like image 37
mario Avatar answered Sep 19 '22 22:09

mario