Random Index in PHP without repeating index

HI, this is the algorithm I create it, hope it will be of good use.

$totalData =count($allData);
	     $randIndex = array();
               for($i=0;$i<$totalData;$i++)
               {
                $randIndex[$i]= rand(0,$totalData-1)  ;
                 do{
				  $hasIt = false;
                  for($j=0;$j<$i;$j++)
                   {
                    if($randIndex[$j]==$randIndex[$i])
		    {
		 $randIndex[$i]=rand(0,$totalData-1)  ;
		 $hasIt = true;
		   }

                   }
                   }while($hasIt);
                }
SO, for your output result:
for($i=0;$i<$totalData;$i++)
{
echo $randIndex[$i];
}
Advertisement
By Oudom Posted in PHP

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s