tortuga
tortuga

Reputation: 17

print random string from string with multiply words

I am new to php and trying out some different things. I got a problem with printing a random value from a string from multiply values.

    $list = "the weather is beautiful tonight".
    $random = one random value from $list, for example "beautiful" or "is"

Is there any simple way to get this done? Thanks!

Upvotes: 0

Views: 50

Answers (2)

ob_start
ob_start

Reputation: 276

// First, split the string on spaces to get individual words
$arg = explode(' ',"the weather is beautiful tonight");

// Shuffle the order of the words
shuffle($arg);

// Display the first word of the shuffled array
print $arg[0];

Upvotes: 0

bibiki
bibiki

Reputation: 13

well, as @Dagon suggested, you can use explode() to get an array of strings, then you can use rand($min, $max) to get an integer between 0 and the length of your array - 1. and then read the string value inside your array at the randomly generated number position.

Upvotes: 1

Related Questions