Php method for obtaining a random element from an array

Source: Internet
Author: User
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:

  1. $ A = array ("a" => "Dog", "B" => "Cat", "c" => "Horse ");
  2. Print_r (array_rand ($ a, 1 ));
  3. ?>
  4. // Output: B

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.