Jump to content

array_rand


boredidiot

Recommended Posts

I cannot get this code to work. It keeps coming back Warning: array_rand() [function.array-rand]: Second argument has to be between 1 and the number of elements in the array.

 

$numb is coming back '1','2','3'

 

 

 

$q = "SELECT * FROM `filler` WHERE `t`='l'";

$r = mysql_query($q) or die(mysql_error());

while ($num = mysql_fetch_assoc($r)) {

$numb .= "'".$num['id']."',";

}

$numb = substr_replace($numb, "", -1);

 

//pick only 2 and no duplicates

$numbers=array($numb);

 

//Get 2 unique random keys from $numbers array.

$rand_keys = array_rand($numbers, 2);

Link to comment
https://forums.phpfreaks.com/topic/164476-array_rand/
Share on other sites

What do you believe this line of code is actually doing???

//pick only 2 and no duplicates
$numbers=array($numb);

Your array comprises a single element, a string value that looks something like '1,2,3'

simply saying $numbers=array($numb) doesn't automatically convert the string into an array of values split on the ,

 

q = "SELECT * FROM `filler` WHERE `t`='l'";
$r = mysql_query($q) or die(mysql_error());
$numbers = array();
while ($num = mysql_fetch_assoc($r)) {
   $numbers[] = $num['id']; 
}

//Get 2 unique random keys from $numbers array.
$rand_keys = array_rand($numbers, 2);

Link to comment
https://forums.phpfreaks.com/topic/164476-array_rand/#findComment-867657
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.