Create foreach loop that only prints the name if it begins with the letter "M"

The following is an array in php.
*/
$loonyToons = array(
“Bugs Bunny”,
“Claude Cat”,
“Daffy Duck”,
“Elmer Fudd”,
“Marvin the Martian”,
“Merlin the Magic Mouse”,
“Michigan J. Frog”,
“Pepe Le Pew”,
“Porky Pig”,
“Road Runner”,
“Sylvester”,
“Tweety Bird”,
“Wile E. Coyote”,
“Yosemite Sam”,
“Tasmanian Devil”
);

Yep, that’s an array. Most of us here already know that. Usually people ask questions when they post here.

Thank you haha!!!
But I need help creating a foreach loop that only prints the words in the array that start with the letter M.

Oh, ok. What have you tried?

Been trying everything
foreach($loonyToons as $word){
$firstLetter = substr($word, 0, (1));
$loonyToons [$firstLetter][] = $word
;
}
echo “

”;print_r($loonyToons);
?>
foreach ($loonyToons as $word) {
    if (substr($word, 0, 1) == 'M') {
        echo $word;
    }
}

YOU are my HERO!!!
I’m so new to this its Greek.
Thank you!!!

1 Like

But wait! That’s not all…

<?php

$loonyToons = [
  "Bugs Bunny"
, "Claude Cat"
, "Daffy Duck"
, "Elmer Fudd"
, "Marvin the Martian"
, "Merlin the Magic Mouse"
, "Michigan J. Frog"
, "Pepe Le Pew"
, "Porky Pig"
, "Road Runner"
, "Sylvester"
, "Tweety Bird"
, "Wile E. Coyote"
, "Yosemite Sam"
, "Tasmanian Devil"
];
print_r(preg_grep('~^M~', $loonyToons ));

Not done yet…
(For Php ver < 7.2.0)

<?php

$loonyToons = [
  "Bugs Bunny"
, "Claude Cat"
, "Daffy Duck"
, "Elmer Fudd"
, "Marvin the Martian"
, "Merlin the Magic Mouse"
, "Michigan J. Frog"
, "Pepe Le Pew"
, "Porky Pig"
, "Road Runner"
, "Sylvester"
, "Tweety Bird"
, "Wile E. Coyote"
, "Yosemite Sam"
, "Tasmanian Devil"
];

print_r(array_filter($loonyToons, create_function('$a', 'return $a[0] == "M";')));

Uh oh, still not done…

<?php

$loonyToons = [
  "Bugs Bunny"
, "Claude Cat"
, "Daffy Duck"
, "Elmer Fudd"
, "Marvin the Martian"
, "Merlin the Magic Mouse"
, "Michigan J. Frog"
, "Pepe Le Pew"
, "Porky Pig"
, "Road Runner"
, "Sylvester"
, "Tweety Bird"
, "Wile E. Coyote"
, "Yosemite Sam"
, "Tasmanian Devil"
];

$result = array_filter($loonyToons, function ($w) {
    return substr($w, 0, 1) == 'M';
});
var_dump($result);

oops! applying now…

Ok I see what you did, arriving at the somewhat same results multiple ways. I truly appreciate it. You just taught me more than I’ve learned in school for the past 2 weeks. Thank you soooo much!!!

You can go back and teach your instructor a few things now.

Oh yeah?!

$result = array_filter($loonyToons, fn($w) => $w[0] === 'M');

Nice comeback Mr. 7.4 :+1:

LOL well, you know more than you did!

Thank you for that! Makes me feel like I may actually be able to do this stuff :slight_smile:

This is great! Thank you!!!

Sponsor our Newsletter | Privacy Policy | Terms of Service