Php generate random and different numbers

I create this in php for generate random numbers

> <?php
> 
> $products=array("1","2","3","4","5","6","7","8","9","10");
> 
> for ($i=0;$i<count($products);$i++) {
> 
> $numbers=rand(0,count(products));
> 
> print "".$products[$numbers]."<br>";
> 
> } ?>

I try generate in bucle different numbers but always show me the same numbers 1212121212 and nothing more , how i can generate this string or array and for example finally show 2 3 4 1 5 6 7 9 8 10 , and if reload script other combination

Thank´s Regards !!!

Upvotes: 0

Views: 1419

Answers (2)

Teena Thomas
Teena Thomas

Reputation: 5239

Try using shuffle,

$products=array("1","2","3","4","5","6","7","8","9","10"); 
shuffle($products);
foreach($products as $v)
 echo $v; 

Demo

Upvotes: 1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324820

You forgot the $ in count($products). As a result, the parser is treating it as the string "products", which has a count() of 1. Therefore, the rand() function returns zero or one, which in your original array correspond to "1" and "2".

Upvotes: 2

Related Questions