Reputation: 300
I am trying to create a PHP function with 2 parameters. One parameter is a variable and the second is an array like this
<?php
function Myfunction($variable, $array=array()){
foreach($array as $item){
echo $variable;
echo $item;
}
}
?>
I want a call like this:
<?php
Myfunction(blue, 1,3,6,10,5);
?>
"blue" is the variable "numbers" insert in an array.
I tried something but it does not work.
Who can help me with this?
Upvotes: 1
Views: 34
Reputation: 4587
Well, there are two possibilities:
You can wrap your values in an array (ie: []
), which I believe is what you intended:
Myfunction(blue, [1,3,6,10,5]);
Or you could take advantage of PHP's variable argument list and have your function parameters listed like so:
Myfunction($variable, ...$array);
Note the ...
before $array
, this signifies that this parameter will accept a variable number of arguments. Keep in mind that parameter using ...
must be the last parameter in your argument list.
With this, you may call your function like so:
Myfunction(blue, 1,3,6,10,5);
Hope this helps,
Upvotes: 1