Cristian Bustos
Cristian Bustos

Reputation: 369

Get random item after applying strlen in for loop

I'm trying to get a random element of an array after applying strlen within the loop FOR to see that words are greater than 5 characters, but at the moment I do not get the expected result.

My code is as follows:

$input = array("Neo", "Morpheus", "Trinity", "Cypher", "Tank");

for ($i=0; $i < count($input); $i++) {

   if(strlen($input[$i]) > 5)
   {
      $rand_keys = array_rand($input, 1);
      echo $input[$rand_keys];
   }
}

but failed at the time to get the random element and I returned several, besides not even function applies strlen

As I can get a random array element after applying strlen to verify that element is greater than 5 characters?

Thanks friends.

Upvotes: 2

Views: 88

Answers (3)

Will
Will

Reputation: 24699

First, create a new array that only contains the elements longer than 5 characters, using array_filter():

$filteredInput = array_filter($input, function ($str) {
    return strlen($str) > 5;
});

Then, use array_rand() as you were originally thinking:

$randomElement = $filteredInput[array_rand($filteredInput, 1)];

Upvotes: 2

splash58
splash58

Reputation: 26153

Make new array with element which length more that 5, and randomize by shuffle function

$res = array_filter($input, function ($i) { return strlen($i) > 5; });
shuffle($res);

if you want only one element, you can take it by $elem = array_shift($res)

demo

Upvotes: 0

BociucH
BociucH

Reputation: 119

for ($i=0; $i < count($input); $i++){

    $rand_keys = array_rand($input, 1);
    if (strlen($input[$rand_keys]) > 5){
        echo $input[$rand_keys];
    }

}

Like this?

Upvotes: 0

Related Questions