Randomize HTML string output

<?php 
    $random1 = '<p>Quotes van de fans:</p><h2>Why join the navy<BR />if you can be a pirate.</h2><h3>Steve jobs</h3>';
    $random2 = '<p>Quotes van de fans:</p><h2>Lorem2</h2><h3>Steve jobs</h3>';
    $random3 = '<p>Quotes van de fans:</p><h2>Lorem3</h2><h3>Steve jobs</h3>';
    echo(rand($random1, $random2, $random3));
?>

So I’ve written the code above. I want my code to randomize the quote that appears. Would there be an user-friendly way of implementing this in a website?

I’m building a website in WordPress and I was wondering if WordPress (or PHP) had an easier method of randomizing output.

Related posts

Leave a Reply

4 comments

  1. Alternatively, you could define an array which contains HTML strings and then use an array_rand() function to get a random entry/element. Example:

    // set of elements with random quotes
    $quotes = array(
        '<p>Quotes van de fans:</p><h2>Why join the navy<BR />if you can be a pirate.</h2><h3>Steve jobs</h3>',
        '<p>Quotes van de fans:</p><h2>Lorem2</h2><h3>Steve jobs</h3>',
        '<p>Quotes van de fans:</p><h2>Lorem3</h2><h3>Steve jobs</h3>',
    );
    
    // apply array_rand function
    echo $quotes[array_rand($quotes)];
    
  2. $random = array();
    
    $random[] = '<p>Quotes van de fans:</p><h2>Why join the navy<BR />if you can be a pirate.</h2><h3>Steve jobs</h3>';
    $random[] = '<p>Quotes van de fans:</p><h2>Lorem2</h2><h3>Steve jobs</h3>';
    $random[] = '<p>Quotes van de fans:</p><h2>Lorem3</h2><h3>Steve jobs</h3>';
    
    shuffle($random);
    
    foreach($random as $quote)
    {
        echo $quote;
    }
    
  3. I would use something like this:

    <?php 
    $quotes = array(
        '<p>Quotes van de fans:</p><h2>Why join the navy<BR />if you can be a pirate.</h2><h3>Steve jobs</h3>',
        '<p>Quotes van de fans:</p><h2>Lorem2</h2><h3>Steve jobs</h3>',
        '<p>Quotes van de fans:</p><h2>Lorem3</h2><h3>Steve jobs</h3>'
    );
    
    echo($quotes[mt_rand(0, (count($quotes) - 1))]);
    

    ?>

  4. You could also do this clean and simply:

    $quotes = array(
        '<p>Quotes van de fans:</p><h2>Why join the navy<BR />if you can be a pirate.</h2>    <h3>Steve jobs</h3>',
        '<p>Quotes van de fans:</p><h2>Lorem2</h2><h3>Steve jobs</h3>',
        '<p>Quotes van de fans:</p><h2>Lorem3</h2><h3>Steve jobs</h3>',
    );
    
    echo $quotes[rand(0,2)]; // 0-2 (Since array's start on 0)