Jump to content

How do you show only 1 random result from foreach loop?


imgrooot

Recommended Posts

I have a foreach loop that returns 5 users. I basically want to show only 1 of the 5 users. Every time that loop is run, it should show a random user of the 5, as oppose to the same user every single time.

How can that be done?  This is my query so far.

$find_user = $db->prepare("SELECT user_id FROM users ORDER BY user_id ASC");
$find_user->execute();
$result_user = $find_user->fetchAll(PDO::FETCH_ASSOC);
if(count($result_user) > 0) {
  foreach($result_user as $row) {
    $user_id   =  trim($row['user_id']);

    var_dump($user_id);
  }
}
Link to comment
Share on other sites

Hopefully you learned a valuable technique from Benanamen's code.  

 

With that said, assuming you wanted to stay with the technique you were using, I think you were looking for the rand() function.  You need to specify in this instance, a min and max to constrain the range of the random number returned.  You have a zero based array so you want 0.. count -1;

$find_user = $db->prepare("SELECT user_id FROM users ORDER BY user_id ASC");
$find_user->execute();
$result_user = $find_user->fetchAll(PDO::FETCH_ASSOC);
//$result_user is an array of all the rows!
$row_count = count($result_user);
if ($row_count > 0) {
    echo $result_user[rand(0, $row_count -1)]['user_id'];
}
Link to comment
Share on other sites

If you only want ONE random record then just ask for it. No need for code gymnastics.

SELECT user_id FROM users ORDER BY RAND() LIMIT 1

FYI: Your data should have been trimmed on input.

 

 

 

No you dont.

 

Ah yes the RAND() does the trick.  

 

Yes my data is trimmed on the input. I guess I don't need to trim it on the output as well.

Link to comment
Share on other sites

 

Hopefully you learned a valuable technique from Benanamen's code.  

 

With that said, assuming you wanted to stay with the technique you were using, I think you were looking for the rand() function.  You need to specify in this instance, a min and max to constrain the range of the random number returned.  You have a zero based array so you want 0.. count -1;

$find_user = $db->prepare("SELECT user_id FROM users ORDER BY user_id ASC");
$find_user->execute();
$result_user = $find_user->fetchAll(PDO::FETCH_ASSOC);
//$result_user is an array of all the rows!
$row_count = count($result_user);
if ($row_count > 0) {
    echo $result_user[rand(0, $row_count -1)]['user_id'];
}

Looks interesting. Will give it a shot. Thanks.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.