Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP PHP Functions Introducing Functions PHP Function Arguments

Amy Hsieh
Amy Hsieh
6,023 Points

I think I got the same code, but result is different

function hello($arr){ if (is_array($arr)){ foreach ($arr as $name){ } echo "Hello, $name <br>"; }else echo'Hello, Friends'; } $names=array ( "John","Mike","Charley");

hello($names);

My result : Hello Charley. It seems I have the same code as the example, but why the code can't print 'Hello John' and 'Hello Mike'?

Damy Bosch
Damy Bosch
2,248 Points

Hello,

Your foreach is empty.

The echo "Hello, $name<br>" is outside your foreach

1 Answer

jamesjones21
jamesjones21
9,260 Points

Hi Amy

your setup should be like this:

function hello($arr){

     if (is_array($arr)){
        $names=array ( "John","Mike","Charley");
          foreach ($arr as $name){  
            echo "Hello, $name <br>";
        } 
    } else {
        echo'Hello, Friends';
    }
}

the echo within the foreach is outside of the foreach loop that's why the results contained nothing.