image . "; echo($url); endforea...">

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 output order. Before the foreach statement, I tried to shuffle the array using shuffle ($ bb); but it didn’t work. Any help is appreciated.

+4
source share
6 answers

Since $ bb is an array of anb arrays, shuffle () will not randomize a sub-array attempt

 shuffle($bb['slides']); 
+9
source

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

 shuffle($bb['slides']); foreach($bb['slides'] as $b): 
+2
source
 shuffle($array_name); // will shuffle array 

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

In addition, foreach should be

 for($array_name as $array_item) { // do stuff } 
+1
source
 <?php shuffle($bb['slides']); foreach($bb['slides'] as $b) { echo $url = "domain.com/" . $b->image . "; } ?> 

Check out this blog for an example explanation.

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

+1
source

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

0
source

Display content in random order

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

Show images randomly

 <?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" />'; } ?> 
0
source

Source: https://habr.com/ru/post/1344030/


All Articles