Jump to content

[SOLVED] Optional function paremeters


play_

Recommended Posts

Say i have a function that takes 1 required parameter and 4 optional ones..

 

function Hello( $name, $age = 'n\a', $job = 'n\a', $status = 'n\a', $car = 'n\a) {

  ...

}

 

 

Now when i call the function, say i want to show his name, and car only. skipping all optional params in between.

 

Is there another way than doing it like

 

Hello('John', '', '', '', 'Honda');

 

which wouldn't even work because that would repalce all 'n\a' with ''.

 

So what's the best way of doing this? (working with functions that take multiple optional params)

Link to comment
https://forums.phpfreaks.com/topic/101832-solved-optional-function-paremeters/
Share on other sites

Are you sure that's what you want to do?

 

Try this

 

<?php

function test ( $var1 = 'n/a', $var2 = 'n/a', $var3 = 'n/a' ) {
echo $var1 . '<br>';
echo $var2 . '<br>';
echo $var3 . '<br>';
}

test(NULL, NULL, 'test');

?>

 

Returns

 

<br><br>test<br>

 

Not

 

n/a<br>n/a<br>test<br>

 

As you'd expect. You have to call it wit the n/a's. Another way to do it is this:

 

<?php

function test ( $var1 = FALSE, $var2 = FALSE, $var3 = FALSE ) {
// If $var1 is not false or empty (?) return $var1, else ( return 'n/a'
echo $var1 ? $var1 : 'n/a' . '<br>';
echo $var2 ? $var2 : 'n/a' . '<br>';
echo $var3 ? $var3 : 'n/a' . '<br>';
}

test(FALSE, NULL, 'test');

?>

 

Returns

 

n/a<br>n/a<br>test

 

Hope that helps.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.