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

Alex Rodriguez
seal-mask
.a{fill-rule:evenodd;}techdegree
Alex Rodriguez
Front End Web Development Techdegree Student 20,810 Points

Why use $names?

I am having a some difficulty understanding why we created an array named $names then transfer that to the function hello which is then converted into $arr. Why not just name the array $arr from the begging and transfer that to hello. I am not sure whats the point of $names is. When I changed the code it still worked. See below. Why do this??

<?php

function hello($arr){ if(is_array($arr)) { foreach($arr as $name) { echo "Hello there $name, how's it going bud?</br>"; } } else { echo 'Hello friends!'; }

}

$names = array ( 'Kevin', 'James', 'Alex', 'Peter', 'Scott', 'Pedro', 'Juan' );

hello($names);

?>

Instead of this?

<?php

function hello($arr){ if(is_array($arr)) { foreach($arr as $name) { echo "Hello there $name, how's it going bud?</br>"; } } else { echo 'Hello friends!'; }

}

$arr = array ( 'Kevin', 'James', 'Alex', 'Peter', 'Scott', 'Pedro', 'Juan' );

hello($arr);

?>

It doesn't really matter. It's a bit easier to read, if you name the list of names as $names. But in that case I'd rather have a hello($names) function. Any way, both options will work

1 Answer

Robert Kulagowski
Robert Kulagowski
4,954 Points

I think that what they were trying to demonstrate is that the array that's internal to the function $arr is a copy of the data that's in $names. You could of course had the function be hello($names) but then that may lead you to believe that the name of the array inside the function had to be the same, when it doesn't. If the function is doing something generic to any array, then calling the array $names inside the function may be confusing if the array isn't full of first names. You could have called the array $a or $foo or $dsfhksjdhfksjhfkh and it wouldn't matter.

Later on there's probably a module on how you can can pass the array as copy-by-reference instead of copy-by-value (which is the default) so that any array manipulation you do inside the function is reflected outside of the function because you're working on the actual array and not a copy of it.