user663561
user663561

Reputation: 190

Shuffle an array in PHP

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.

Upvotes: 5

Views: 16851

Answers (6)

Meberem
Meberem

Reputation: 947

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']);

Upvotes: 10

Porta Shqipe
Porta Shqipe

Reputation: 866

Display content at random order

<?php
$myContentList = array (
    'One',
    'Two',
    'Three',
    'Four'
);
shuffle ($myContentList);
foreach ($myContentList as $displayAtRandomOrder) {
echo '<div>' . $displayAtRandomOrder . '</div>';
}
?>

Display images at random order

<?php
$myImagesList = array (
    'one.png',
    'two.png',
    'three.jpg',
    'four.gif'
);
shuffle ($myImagesList);
foreach ($myImagesList as $displayImagesAtRandomOrder) {
echo '<img src="images/' . $displayImagesAtRandomOrder . '" width="200" height="40" border="0" />';
}
?>

Upvotes: 0

Prashant Patil
Prashant Patil

Reputation: 11

<?php
shuffle($bb['slides']);
foreach($bb['slides'] as $b) {
    echo $url = "domain.com/" . $b->image . ";
}
?>

Check this blog for explanation with example.

http://wamp6.com/php/str_shuffle-php/ Check for array shuffle

Upvotes: 1

mario
mario

Reputation: 145512

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

shuffle($bb['slides']);
foreach($bb['slides'] as $b):

Upvotes: 2

Brian
Brian

Reputation: 3601

Looks like you need to do shuffle( $bb['slides'] ).

Upvotes: 0

Chris
Chris

Reputation: 58322

shuffle($array_name); // will shuffle array

http://www.php.net/manual/en/function.shuffle.php

Also the foreach should be

for($array_name as $array_item) {
// do stuff
}

Upvotes: 1

Related Questions