0

I'm having a problem when using array_rand.

The thing is that I called some values from my database into an array, and then I did array_rand to randomly select one of those values (you don't say).

$query = mysqli_query($con,"SELECT * FROM random");

while ($row = mysqli_fetch_assoc($query)) {
    $num[] = $row["id"];
}

If I do a print_r($num);, I get the following:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
    [6] => 7
    [7] => 8
    [8] => 9
    [9] => 10
    [10] => 11
    [11] => 12
    [12] => 13
    [13] => 14
)

But when doing array_rand($num);, one of the values that I randomly get is 0, which as you can see, is not in the list, therefore the rest of the code that uses this random value won't work if it cames up with it.

I searched in Google for this problem, but couldn't find a solution, I'm sorry if this has been mentioned before.

Hopefully you can help me fix this problem.

Thanks in advance.

0

3 Answers 3

2

As the document said, array_rand() returns the key for a random entry.

So you have to do with $num[array_rand($num)] to get the value.

Sign up to request clarification or add additional context in comments.

1 Comment

Oh I see, any other function that I could use?
1

In this case, why not use RAND() in your query and save some work & resources?

$query = mysqli_query($con, "SELECT * FROM random ORDER BY RAND() LIMIT 1");
$result = mysqli_fetch_object($query);

2 Comments

Yup, thanks. I'm kinda new to PHP + MySQL and I keep forgeting that I can do this stuff with MySQL.
@user2077474 I've only recently started getting comfortable with MySQL - I used to leave a lot up to PHP as well (anything other than basic sorting, joining data, etc). You'll be surprised by how much MySQL can be responsible for.
0

From the documentation of array_rand (emphasis added):

Picks one or more random entries out of an array, and returns the key (or keys) of the random entries.

0 is the key of your first element being returned

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.