1
        $stmt = $web_dbi->prepare($query);
        $stmt->execute();
        $result = $stmt->get_result();  
        $num_of_rows = $result->num_rows;   

        while($row=mysqli_fetch_array($result)){
          $results[] = $row;
        }

        $randomNumber = mt_rand(0,($num_of_rows-1));
        if($results[$randomNumber]['mysql_field']==anothervalue){
        ...

how do I access, at random, a given element of $results[]? Is this syntax correct in this scenario?

3 Answers 3

2

Your code looks fine. I personally prefer using array_rand to select a random element from the array:

$random_value = $results[array_rand($results)];
Sign up to request clarification or add additional context in comments.

Comments

1
shuffle($results);
$item_to_use = array_pop ($results);

Not the most efficient but uses fewer lines of code.

Comments

1

Alternativley, you can use sql query to get random result.

SELECT field1, field2, field3 FROM table_name ORDER BY RAND()

Or to get random array element from PHP array try this,

echo $results[mt_rand(0, $num_of_rows - 1)]['mysql_field'];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.