David19801
David19801

Reputation: 11448

How can I get a random word that starts with a given letter from an array in PHP?

I an array of 20 words in PHP. Is there a way to extract a random word from this array that starts with a specific letter?

For example if I want a word starting with B say.

$arr=array('apple','almond','banana','boat','carrot');

Then it will return banana half the time, or boat half the time.

How can I get a random word starting with a given letter from this array?

Upvotes: 1

Views: 275

Answers (3)

Tech163
Tech163

Reputation: 4286

This should work. After shuffling the array, each word starting with 'B' or whichever letter will have a random chance of being first in the shuffled array. Relying on PHP's shuffle() is probably more efficient and faster than our own implementation.

function returnWithFirstLetter($words, $letter) {
    shuffle($words);
    foreach($words as $word)
        if($word[0] == $letter)
            return $word;
}

Upvotes: 2

moonwave99
moonwave99

Reputation: 22817

Quick & dirty, here you go:

function returnRandomWithLetter($words, $letter)
{

    // put all words in different bins, one for each different starting letter
    $bins = array();

    foreach($words as $word)
    {

        $bins[$word[0]][] = $word;

    }

    // return random component from chosen letter's bin 
    return $bins[$letter][array_rand($bins[$letter])];

}

Upvotes: 0

Hagen von Eitzen
Hagen von Eitzen

Reputation: 2177

The following works even with methods of selecting eligible words that are more complicate than just "check the first letter" and does not rely on e.g. all eligible words being consecutive in the array.

$candidatestested = 0;
foreach ($arr as $candidate) {
   if ($candidate[0] == 'b' && rand(0,$candidatestested++)==0) {
       $result = $candidate;
   }
}
if (!$candidatestested) {
   trigger_error("There was no word matching the criterion");
}
return $result;

Upvotes: 3

Related Questions