Reputation: 99
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
Reputation: 4211
$random=shuffle($matches) ?: array_rand($matches,1);
$firstRandom=$random[0]:
?: is operetaror shortly if operator
Upvotes: 0
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