1

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?

2
  • Maybe this Myfunction('blue', array(1,3,6,10,5)); will help. Commented Mar 8, 2019 at 22:07
  • Simple, just call it like this MyFunction(blue, [1,3,6,10,5]); Commented Mar 8, 2019 at 22:10

1 Answer 1

1

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,

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Miroslav for the solution! I made the function with the advanced option :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.