How to get the indexes of words from an array of strings that start with a specific letter in PHP

1 Answer

0 votes
function getIndexesOfWordsStartingWith($array, $letter) {
    $indexes = [];
    
    foreach ($array as $index => $word) {
        if (stripos($word, $letter) === 0) {
            $indexes[] = $index;
        }
    }
    
    return $indexes;
}

$stringArray = ["zero", "one", "two", "three", "four", "five", 
                "six", "seven", "eight", "nine", "ten"];
$specificLetter = 't';

$indexes = getIndexesOfWordsStartingWith($stringArray, $specificLetter);

print_r($indexes); 



/*
run:

Array
(
    [0] => 2
    [1] => 3
    [2] => 10
)

*/

 



answered Mar 14, 2025 by avibootz
...