Alim Qureshi
Alim Qureshi

Reputation: 29

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

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

<?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

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?

Upvotes: 1

Views: 66

Answers (2)

AbraCadaver
AbraCadaver

Reputation: 78994

Here are two ways using array_chunk() so that the two stay matched:

$names = array_chunk($names, 2);
$rand  = $names[array_rand($names)];
echo $rand[0] . $rand[1];

Or:

$names = array_chunk($names, 2);
shuffle($names);
echo $names[0][0] . $names[0][1];

Upvotes: 0

Don&#39;t Panic
Don&#39;t Panic

Reputation: 41810

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>';
}

Upvotes: 2

Related Questions