Sam
Sam

Reputation: 15518

How to echo randomly a portion of a string?

i have already succesfully translated some quotes via my translation function __(); and now I want to echo only one of those quotes at random. All quotes are separated in this string with a special character like a |

Sofar I only have this. What code could should go below this tackle my random echo?

$quotes =
__("IF YOU MAKE EVERYTHING BOLD, NOTHING IS BOLD") . "|" .
__("Quality of design is an indicator of credibility") . "|" .
__("People ignore design, that ignores people");

(An important restriction: it is essential that the quotes be exactly closed with __(" and "); sothat they can be checked and translated.) __($variable) doest not work with current clean up scripts that I have bought so these won't work.

Upvotes: 0

Views: 120

Answers (3)

John Flatness
John Flatness

Reputation: 33829

You're already calling __() on each of your quotes individually, why not save all the extra translating and do something like:

$quotes = array('quote1', 'quote2', 'quote3');
$index = array_rand($quotes);
echo __($quotes[$index]);

Edit: To satisfy your other requirement, that the call to __() must immediately surround each string, you could do this:

$quotes = array(__('quote1'), __('quote2'), __('quote3'));
$index = array_rand($quotes);
echo $quotes[$index];

The big downside here is that you're now looking up a translation for every string in that array, even though only one is printed, but that's the same situation you had in the "one big string" solution.

Upvotes: 2

Stefan Kendall
Stefan Kendall

Reputation: 67892

Why the biscuits are they all in one string, and not an array? Your problem would be immediately solved if this was the case. As stands, split in | and index randomly into the array created to pick a random quote.

Upvotes: 1

Alin P.
Alin P.

Reputation: 44386

Why don't you keep them in an array and translate only what is actually outputted?

$quotes = array(
    "IF YOU MAKE EVERYTHING BOLD, NOTHING IS BOLD",
    "Quality of design is an indicator of credibility",
    "People ignore design, that ignores people",
);
$randomQuote = $quotes[ rand(0, count($quotes)-1)];
echo __($randomQuote);

Upvotes: 1

Related Questions