Harrison
Harrison

Reputation: 99

Select 1 single random result from Foreach

I have the code below, which is working perfectly for returning all of the files from our $base location. However, I am wondering how we can select only one random result from this and display it on the page.

There's 44 total results for it to shuffle from, and I want it to display a random account each time a user views the page.

$red = file_get_contents($base);
$matches = explode(PHP_EOL, $red);
foreach ($matches as $match){
    $match_explode_1 = explode(' password:', $match);
    $match_explode_2 = explode(' username:', $match_explode_1[0]);
    $data['email_addresss'] = str_replace('email:', '', $match_explode_2[0]);
    $data['username'] = $match_explode_2[1];
    $data['password'] = base64_encode($match_explode_1[1]);

    print '<pre>';
    print_r($data); 
    print '</pre>';
}

Upvotes: 2

Views: 227

Answers (2)


$random=shuffle($matches) ?:  array_rand($matches,1);
$firstRandom=$random[0]:

?: is operetaror shortly if operator

Upvotes: 0

Nick
Nick

Reputation: 147206

There are a couple of possibilities for selecting a single random value from an array. You can use shuffle to randomise the array, and then take the first element. Or you can use array_rand to pick a random key in the array. For example:

shuffle($matches);
$match = $matches[0];

or

$match = $matches[array_rand($matches)];

Upvotes: 1

Related Questions