Reputation: 1027
getAllForms($data=null)
getAllForms() and getAllForms("data")
This will work. But I want to make two optional argument in a function like this:
getAllForms($arg1=null,$arg2=null)
getAllForms() and getAllForms("data")
How can I make this possible?
Upvotes: 4
Views: 13760
Reputation: 95121
You can try:
function getAllForms() {
extract(func_get_args(), EXTR_PREFIX_ALL, "data");
}
getAllForms();
getAllForms("a"); // $data_0 = a
getAllForms("a", "b"); // $data_0 = a $data_1 = b
getAllForms(null, null, "c"); // $data_0 = null $data_1 = null, $data_2 = c
Upvotes: 11
Reputation: 15047
<? php
function getAllForms($data1 = null, $data2 = null)
{
if ($data1 != null)
{
// do something with $data1
}
if ($data2 != null)
{
// do something with $data2
}
}
?>
getAllForms();
getAllForms("a");
getAllForms(null, "b");
getAllForms("a", "b");
or
<? php
function getAllForms($data = null)
{
if (is_array($data))
{
foreach($data as $item)
{
getAllForms($item);
}
}
else
{
if ($data != null)
{
// do something with data.
}
}
}
getAllForms();
getAllForms("a");
getAllForms(array("a"));
getAllForms(array("a", "b"));
?>
Upvotes: 1
Reputation: 17910
You can also try using func_get_arg
which you can pass n
number of arguments to a function.
http://php.net/manual/en/function.func-get-args.php
Example
function foo(){
$arg_list = func_get_args();
for ($i = 0; $i < $numargs; $i++) {
echo "Argument $i is: " . $arg_list[$i] . "<br />\n";
}
}
foo(1, 2, 3);
Upvotes: 6
Reputation: 4923
You already described how you would do it:
function getAllForms($arg1 = null, $arg2 = null)
Except the every variable name (including the second) has to be different.
Upvotes: 1
Reputation: 35973
Try this:
getAllForms($data=null,$data2=null)
and you call it in this mode:
getAllForms()
getAllForms("data")
getAllForms("data","data2")
The second argument have to be different name respect the first
Upvotes: 3