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

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.