PHP - shuffle array


I'm scheduling a news feed page in PHP .

I ask your help to help me shuffle the $tagsArray array so that the posts are not always in the same order.

Thank you in advance!


    $conexao = mysqli_connect("localhost","root","","newsite");

    $seguindoID= "android,Flash,iPrimePortas,";
    $tagsArray = explode(',', $seguindoID);
    $sizeSeguindo= count($tagsArray) -1;

    for($i=0; $i<=$sizeSeguindo; $i++){
        $sql = "select * from postpagina where pagina='$tagsArray[$i]'";
        $query = mysqli_query($conexao, $sql);

        while($linha = mysqli_fetch_assoc($query)){
            $userPost = $linha['pagina'];
            $post = $linha['post'];

            echo "<div><label>Postado por <b>$userPost</b> - $post</label></div>";
asked by anonymous 19.02.2018 / 22:21

2 answers


You can also use the RAND function of MySQL .

SELECT * FROM postpagina WHERE pagina='$tagsArray[$i]' ORDER BY RAND();

In this way the function mysqli_fetch_assoc , will already return the elements in random order.


19.02.2018 / 22:33

Instead of printing directly, save each one in an array.

$itens[] = "<div><label>Postado por <b>$userPost</b> - $post</label></div>";

Then use one of the functions listed here PHP: Ordering Arrays - Manual

such as:


and print the result using foreach for example:

foreach( $itens as $item){
    echo $item;

will always print in random order

19.02.2018 / 22:29