In php, we use rand () or mt_rand () to generate random data. to obtain random elements of an array, we only need to set rand (0, arrlength) to 0, maximum array length
We use rand () or mt_rand () to generate random data in php. to obtain random elements of the array, we only need to set rand (0, arr. in this case, the starting value is 0, and the maximum value is the length of the array.
Yesterday, I helped the customer modify the sidebar. I thought I could breathe a sigh of relief. as a result, he sent another message and said that he needed to add a tag under each article, the ads for their company's 12 businesses are displayed randomly. If you have determined the requirements, let's get started.
In fact, it is quite simple to predefine an array to store these 12 AD words. the code is as follows:
$ Option = array ('wide www.phpfensi.com word 1', 'ad word 2', 'ad word 3', 'ad word 4', 'ad word 5 ');
Then a subscript is randomly generated. the code is as follows:
$ Index = rand (0, count ($ option)-1); echo $ option [$ index];
In general, it is best to store the data into a database or xml for convenience of expansion, but the idea is the same. except for the above method, we can use the array_rand () function, this function randomly selects one or more elements in the array and returns them.
The instance code is as follows:
- $ A = array ("a" => "Dog", "B" => "Cat", "c" => "Horse ");
- Print_r (array_rand ($ a, 1 ));
- ?>
- // Output: B