Jump to content

[SOLVED] function() question


AV1611

Recommended Posts

I have a function I wrote, but to make the point, here's a simple example.

 

Let's say I do

 

function myfunc($a,$b){

echo $a;

echo $b;

}

 

What I want to do is make $b optional, and if it's not set, for the function to assume a predefined string.  In this case it's a percentage that I use in some css later, so I want the string to default to 100 if $b is not used i.e. myfunc($a) but $b to pass if it's myfunc($a,$b)

 

How do I do that?

 

Thanks.

 

Link to comment
https://forums.phpfreaks.com/topic/145234-solved-function-question/
Share on other sites

Easy enough...

 

<?php
function myfunc($a,$b = '100'){
echo $a;
echo $b;
}

 

Thanks, I found that but it didn't make sense until you just did it :P  I also found this but it's more complex than I need in this case, but is a better answer maybe in some cases:

 

        $numArgs = func_num_args();

 

Thanks.

Be careful with these built in functions such as func_num_args();

 

Because they allow a variety of different inputs so it could be a hassle to trouble issues if your program gets long and complicated.

 

The best way is what GenericNumber posted as his example.

 

Also, functions only accept scalar variables so don't get too carried away...

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.