Skip to content
Advertisement

How to get a specific length of string in my array?

I am generating an integer from 5-10.

once I generate an integer ranging from 5-10, the loop should choose a string on my array that has a character length based on the random integer that is generated.

example:

random integer generated: 10

the system should display a string that has a length of 10 character so either it will display the testNames1 or testNames2 because it has 10 character length

I tried doing this on my code, but it doesn’t work.

<?php
  function getName(){

    $names = array(
        'Juans',
        'Luisss',
        'Pedroaa',
        'testNames1',
        'testNames2',
        'testName3',
        'test', //This should not be return because im only generating a number random of 5-10 and this character has only 4 character length
        'tse', //This should not be return because im only generating a number random of 5-10 and this character has only 3 character length
        // and so on
    );
    
    $randomString = "";
    
    for ($i = 0; $i <count($names); $i++) {
        $value = rand(5,10);
        $length_string = strlen($names[$i]);

        if ($value == $length_string) {
            return "name:".$names[$i].$value;
        }
 
    }

  }

echo getName();
?>

Can anyone help me on how to do this?

Advertisement

Answer

What you need to do is first create a list of strings matching the length and then pick a random one from them. So loop through all of the strings, check the length and add to $match, then use array_rand() to pick one of the matching ones…

function getName($random_num)
{
    $names = array
    (
        'Juans',
        'Luisss',
        'Pedroaa',
        'testNames1',
        'testNames2',
        'testName3',
        'test', //This should not be return because im only generating a number random of 5-10 and this character has only 4 character length
        'tse', //This should not be return because im only generating a number random of 5-10 and this character has only 3 character length
        // and so on
    );
    $randomString = "";
    $match = [];
    foreach ( $names as $name )
    {
        $length_string = strlen($name);
        if ($random_num == $length_string)
        {
            $match[] = $name;
        }
    }
    // If non found return ''
    return !empty($match) ? $match[array_rand($match)] : '';
}

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement