Home >Backend Development >PHP Tutorial >PHP function sample code for randomly outputting famous quotes

PHP function sample code for randomly outputting famous quotes

怪我咯
怪我咯Original
2017-07-07 10:26:561613browse

Just like you can see the famous quotes behind the title of "Xiaotan Blog", a sentence will appear randomly every time it is refreshed. Put your favorite words together and often appear in front of your eyes, giving you warm power

So how is this function of random celebrity quotes implemented?

It's actually very simple. You only need a stringvariable, which contains all the famous quotes to be displayed randomly, and then use explode The function is decomposed into an array, and then a rand random number is used to generate a value and a certain sentence in the array is output.

Go directly to the code:
says.php

The code is as follows:

<?php 
function random_str () { 
$poems="人生的价值,并不是用时间,而是用深度去衡量的。-- 列夫·托尔斯泰 
三人行,必有我师焉。择其善者而从之,其不善者而改之。——孔子 
人生不是一种享乐,而是一桩十分沉重的工作。-- 列夫·托尔斯泰 
成为卓越的代名词,很多人并不需要杰出素质的环境。——Steve Jobs 
活着就是为了改变世界,难道还有其他原因吗?——Steve Jobs 
Follow yourself.追随你的内心。——Steve Jobs 
生活是不公平的;要去适应它。——比尔盖茨 
常常提醒自己注意幸福,就像在寒冷的日子里经常看看太阳,心就不知不觉暖洋洋,亮光光。——毕淑敏 
幸福是一种心灵的振颤。它像会倾听音乐的耳朵一样,需要不断地训练。——毕淑敏 
这世界并不会在意你的自尊。这世界指望你在自我感觉良好之前先要有所成就。——比尔盖茨 
生活只有在平淡无味的人看来才是空虚而平淡无味的。-- 车尔尼雪夫斯基"; 
$poems=explode("\n",$poems); 
return $poems[rand(0,count($poems)-1)]; 
} 
function says(){ 
$says=random_str(); 
echo $says; 
} 
?>


The key lies in these sentences:

The code is as follows:

$poems=explode("\n",$poems); 
return $poems[rand(0,count($poems)-1)];

If you are using the wordpress blog system, you can put the file says.php in the theme root directory, then modify the header.php in the theme root directory and insert a statement Go to the front:

The code is as follows:

<?php include(dirname(file)."/says.php"); ?>

Then insert the following statement where you want to display random celebrity quotes:
says();
This way you can call . I don’t know much about the wordpress system, so this method is definitely not the best way.

The above is the detailed content of PHP function sample code for randomly outputting famous quotes. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn