Jump to content

Recommended Posts

Hello! Thanks in advance.. here's my problem:

 

I want the code to fill the array with 10 unique values from my list. Here's my code now:

$bands = "Bloc Party, Arcade Fire, DFA 1979, Klaxons, Metric, Blur, Small Faces, Smiths, Stripes, Charlatans, MGMT, Strokes";

$bands = explode(", ",$bands);
$amountofbands = count($bands);

$no[] = $bands[rand(0, $amountofbands)];
$no[] = $bands[rand(0, $amountofbands)];
$no[] = $bands[rand(0, $amountofbands)];
$no[] = $bands[rand(0, $amountofbands)];
$no[] = $bands[rand(0, $amountofbands)];
$no[] = $bands[rand(0, $amountofbands)];
$no[] = $bands[rand(0, $amountofbands)];
$no[] = $bands[rand(0, $amountofbands)];
$no[] = $bands[rand(0, $amountofbands)];
$no[] = $bands[rand(0, $amountofbands)];

array_unique($no);

while(count($no) != 10){
$no[] = $bands[rand(0, $amountofbands)];
$no = array_unique($no);
}
print_r($no);

 

This gives me results that sometimes are blank, and there are also duplicates.

 

How can i fix it!??!?!  :facewall: :facewall:

 

Thank you!

 

Snooble

Link to comment
https://forums.phpfreaks.com/topic/169480-solved-unique-random-array-please-help/
Share on other sites

Your blank entries are because count($bands) is one more than the highest array index so randomly you will get a NULL value for a nonexistent array entry.

 

array_unique($no); does nothing because it returns an array that you must do something with.

 

No comment on your while() loop.

 

After you explode() the string, just use shuffle() on the array and then use the first 10 entries.

 

 

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.