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 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');

?>