Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

PHP PHP Functions Introducing Functions PHP Function Default Arguments

Ezra John Alvarez
Ezra John Alvarez
557 Points

What if I dont want to provide value of the first variable?

<?php

function get_info($name = 'friend', $title){ echo "Hi $name, are you a $title?"; }

get_info('','Developer');

?>

Why does this code doesnt work? What im trying to do here is only provide the value of the $title..

2 Answers

Cosmin Cioaclă
Cosmin Cioaclă
21,339 Points

Hi Ezra,

It seems that the way to make this work is to change the order of you variables. You should not set a default for the first argument, but for the second. More info can be found here, example #5.

Hope that helps, Cosmin

Ezra John Alvarez
Ezra John Alvarez
557 Points

Hi Cosmin, so basically, you can only add default value to the last argument or add default value for both but not for the first argument only..

Illustration:

1: ($a, $b = 'default b value') = Correct

2 ($a = 'default a value', $b = 'default b value') = Correct

3 ($a = 'default a value', $b) = Incorrect

Is this correct?

Cosmin Cioaclă
Cosmin Cioaclă
21,339 Points

That seems to be the case, yes.

Hi John,

you have to provide the variable in the function. Why do you use a variable instead of text?

This code should work for you:

<?php

function get_info($title){ 
$name = 'friend';
echo "Hi $name, are you a $title?"; }

get_info('Developer');

?>