Alim Qureshi Alim Qureshi - 2 months ago 12
PHP Question

How can I randomize an array while keeping its elements grouped together?

I was wondering how I could display these 2 arrays at random. I tried to make the random but failed. Here are my files:

PHP File

<?php
$names=file('name.txt');
$fileArray = array_values(array_filter($names, "trim"));
$randomText = $fileArray[0];
$randomText .= $fileArray[1];
?>
<h1>Test: <?php echo $randomText; ?></h1>


name.txt

Alim
Qureshi

Test2
TestTwo

Test3
TestThree

Test4
TestFour

Test5
TestFive


Result: http://imgur.com/FPyXzlp



I want it to display the strings in name.txt at random, but to keep the sets of strings like "Test2 TestTwo" together so that they will be displayed at the same time. How can I do this?

Answer

After you get your values in an array you can use array_chunk to split it into two-item sub-arrays so that the two pieces you want can stay together when it's randomized. Then just shuffle it before you output.

$names = file('name.txt');
$fileArray = array_values(array_filter($names, "trim"));
$fileArray = array_chunk($fileArray, 2);
shuffle($fileArray);

foreach ($fileArray as $chunk) {
    $randomText = $chunk[0];
    $randomText .= $chunk[1];   
    echo $randomText . '<br>';
}
Comments