Search code examples
phprandomcountwords

Show several words randomly with php


I need to show automatic words when loading a page on my site. I have managed to show a word, but I can not see more than one. It is important that the words do not repeat themselves.

I have this code where I specify each word.

<?php


$randomThings = array(
    'random thing 1',    
    'random thing 2',    
    'random thing 3',    
    'random thing 4',    
    'random thing 5',    
    'random thing 6',    
    'random thing 7 ',    
);

?>

And finally I paste this code where I want it to be displayed.

<?php echo $randomThings[mt_rand(0,count($randomThings)-1)]; ?>

As I say, a word shows it to me correctly but I want to show more than one.

Thank you very much, sorry for my English


Solution

  • Here is the snippet, provide number of elements as second parameter in rand_keys:

    <?php
      $input = array(
        'random thing 1',    
        'random thing 2',    
        'random thing 3',    
        'random thing 4',    
        'random thing 5',    
        'random thing 6',    
        'random thing 7 ',    
      );
      $rand_keys = array_rand($input, 2);
      echo $input[$rand_keys[0]];
      echo $input[$rand_keys[1]];
    ?>