0

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
Arkistarvh Kltzuonstev
  • 6,824
  • 7
  • 26
  • 56
  • 1
    have you tried with the `mt_rand()` function? – dwpu Apr 26 '19 at 16:03
  • 1
    **Pro tip:** Beginners are welcome, but we expect a certain amount of effort to be expended on attempting to solve your own problem prior to a question being posted. We dont write code for you although we are very willing to help you fix issues with code you have written. – RiggsFolly Apr 26 '19 at 16:05
  • 1
    Or just Google it and one of the top results is: https://php.net/manual/en/function.array-rand.php – Andreas Apr 26 '19 at 16:10
  • At this time I use this code: // Add more $text[X] = "Random text"; if you want more than six ;) $text[1] = "1"; $text[2] = "2"; $text[3] = "3"; $text[4] = "4"; $text[5] = "5"; // Picking a random number $num = rand(1, count($text)); floor($num); // Showing the text associated with the random number echo $text[$num ]; It works well but only shows one link at a time. How can I show 2 or more links? I'm not familiar with php – Claudio De Paolo Apr 26 '19 at 16:11
  • 2
    Do the same thing twice. Or if I was doing it: `shuffle($array);` then `echo implode("
    ", array_slice($array, 0,2));`
    – Andreas Apr 26 '19 at 16:19

2 Answers2

0

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]] . "\n";
echo $text[$keys[1]] . "\n";

#example 2

$text = array("a", "b", "c", "d", "e");

echo $text[mt_rand(0,4)] . "\n";
echo $text[mt_rand(0,4)] . "\n";

?>
dwpu
  • 258
  • 3
  • 19
0

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]];
Rakesh Jakhar
  • 6,380
  • 2
  • 11
  • 20