0

I'm trying to display blocks of text from a list of blocks.

I'm thinking that an array makes the most sense...

$quotes[] = array(
    'block'  => 'Luck is what happens when preparation meets Opportunity.',
    'author' => 'Seneca',
);
$quotes[] = array(
    'block'  => 'Quote number two.',
    'author' => 'Author Two',
);
$quotes[] = array(
    'block'  => 'Quote number three.',
    'author' => 'Author Three',
);

Now if I wanted to list the quotes I would do this:

foreach($quotes[] as $quote) {
    echo '<div><p>"<i>' . $quote['block'] . '</i>"<br />― ' . $quote['author'] . '</p></div>';
}

But how do I go about listing just one of the quotes randomely?

I was looking around and some people were using while loops?

The end goal is that wherever I place this piece of code, I want to display a random quote in different parts of my website, so I don't want the same quote to be in every spot.

16
  • 1
    shuffle($quotes); then just $displayQuote = array_pop($quotes); and display that one.... shuffle(), array_pop() Commented May 19, 2015 at 21:39
  • 1
    echo $quotes[array_rand($quotes)]; Commented May 19, 2015 at 21:41
  • 1
    you have to store the random key picked then use it, like so: $rand_key=array_rand($quotes); echo $quotes[$rand_key]['block']; echo $quotes[$rand_key]['author']; Alternative: $picked =$quotes[array_rand($quotes)]; echo $picked['block']; $picked['author'] Commented May 19, 2015 at 21:55
  • 1
    Once you select an element, you have an array that you can use just like any other array. Commented May 19, 2015 at 21:59
  • 1
    your demo is missing the [] you use above Commented May 19, 2015 at 22:22

1 Answer 1

1

I believe it's as simple as just getting random integer from 0 to count($quotes).

That could be done like in this question.

In your case:

echo $quotes[rand(0, count($quotes) - 1)]['block'];
Sign up to request clarification or add additional context in comments.

2 Comments

You're not accessing the properties of $quotes.
True story, bro :0) Edited.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.