1
<?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.

0

4 Answers 4

11

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)];
Sign up to request clarification or add additional context in comments.

Comments

0
$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 Comments

This would randomize the array for sure. But display all of the elements
True I misread the question a bit. Could use $random[0] for a random quote.
That, or if you really wish to use a foreach (which I personally wouldn't) use break; after the first iteration so the loop does not repeat
0

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))]);

?>

Comments

0

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)

1 Comment

What if the array expands?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.