play_ Posted April 19, 2008 Share Posted April 19, 2008 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 More sharing options...
chigley Posted April 19, 2008 Share Posted April 19, 2008 Try: <?php function Hello($name, $age = 'n\a', $job = 'n\a', $status = 'n\a', $car = 'n\a') { // ... } Hello($name, NULL, NULL, NULL 'Honda'); ?> Link to comment https://forums.phpfreaks.com/topic/101832-solved-optional-function-paremeters/#findComment-521131 Share on other sites More sharing options...
play_ Posted April 19, 2008 Author Share Posted April 19, 2008 thanks Link to comment https://forums.phpfreaks.com/topic/101832-solved-optional-function-paremeters/#findComment-521295 Share on other sites More sharing options...
discomatt Posted April 19, 2008 Share Posted April 19, 2008 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. Link to comment https://forums.phpfreaks.com/topic/101832-solved-optional-function-paremeters/#findComment-521305 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.