This question already has an answer here:
I have n number of links, each with its own keyword. I would like to show two links at a time, randomly in php. Any suggestion?
Here is input example :
$text[1] = "<a href=https://www.website.ext/post-1/>words 1</a>";
$text[2] = "<a href=https://www.website.ext/post-2/>words 2</a>";
$text[3] = "<a href=https://www.website.ext/post-3/>words 3</a>";
$text[4] = "<a href=https://www.website.ext/post-4/>words 4</a>";
$text[5] = "<a href=https://www.website.ext/post-5/>words 5</a>"
....
output example :
words 1
words 3
or
words 5
words 2
or
words 4
words 1
</div>
You can approach this as
$arr = [
'<a href=https://www.website.ext/post-1/>words 1</a>',
'<a href=https://www.website.ext/post-2/>words 2</a>',
'<a href=https://www.website.ext/post-3/>words 3</a>',
'<a href=https://www.website.ext/post-4/>words 4</a>',
'<a href=https://www.website.ext/post-5/>words 5</a>'
];
$res = array_rand($arr,2);
echo $arr[$res[0]];
echo '<br/>';
echo $arr[$res[1]];
Here is an example of code that you can follow to achive your task. You can use the mt_rand() function to select a random index from the array and then echo it, or the array_rand() function that will extract randomly from the array the given number of elements.
<?php
#example 1
$text = array("a", "b", "c", "d", "e");
$keys = array_rand($text, 2);
echo $text[$keys[0]] . "
";
echo $text[$keys[1]] . "
";
#example 2
$text = array("a", "b", "c", "d", "e");
echo $text[mt_rand(0,4)] . "
";
echo $text[mt_rand(0,4)] . "
";
?>