Jump to content

[SOLVED] Unique Random Array.. Please HELP!


Snooble

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.

 

 

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.