$cnt = count($games); while($l <= 3) // note the 3 here { $random = rand(0, $cnt); if ($games[$random] != $adcode) { $games[$random] = $adcode; $l++; } }