The way PHP obtains a random element from an array

Source: Internet
Author: User

Yesterday to help customers modify the sidebar, thought finally can breathe a sigh of relief, the results came off the clock, he actually sent a message, said that the need to add a label under each article, a random display of their company's 12 business advertising words. Set the demand, then do it.

In fact, it is quite simple to first predefined an array to store these 12 words, such as

The code is as follows

$option = Array (' Guang www.111cn.net word 1 ', ' advertisement Word 2 ', ' advertising word 3 ', ' advertisement word 4 ', ' advertisement word 5 ');

And then randomly generate a subscript,

The code is as follows

$index = rand (0, COUNT ($option)-1);
echo $option [$index];

In general, in order to expand the convenience, it is best to put this data into the database or XML, but the idea is the same.

In addition to the above approach we can use the Array_rand () function, which randomly selects one or more elements in this function array, and returns.

Example 1

The code is as follows

<?php
$a =array ("a" => "Dog", "B" => "Cat", "C" => "horse");
Print_r (Array_rand ($a, 1));
?>

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.