Can we pass an array as parameter in any function in PHP?
Solution 1
You can pass an array as an argument. It is copied by value (or COW'd, which essentially means the same to you), so you can array_pop()
(and similar) all you like on it and won't affect anything outside.
function sendemail($id, $userid){
// ...
}
sendemail(array('a', 'b', 'c'), 10);
You can in fact only accept an array there by placing its type in the function's argument signature...
function sendemail(array $id, $userid){
// ...
}
You can also call the function with its arguments as an array...
call_user_func_array('sendemail', array('argument1', 'argument2'));
Solution 2
even more cool, you can pass a variable count of parameters to a function like this:
function sendmail(...$users){
foreach($users as $user){
}
}
sendmail('user1','user2','user3');
Solution 3
Yes, you can do that.
function sendemail($id_list,$userid){
foreach($id_list as $id) {
printf("$id\n"); // Will run twice, once outputting id1, then id2
}
}
$idl = Array("id1", "id2");
$uid = "userID";
sendemail($idl, $uid);
Solution 4
Yes, you can safely pass an array as a parameter.
Solution 5
What should be clarified here.
Just pass the array when you call this function.
function sendemail($id,$userid){
Some Process....
}
$id=array(1,2);
sendmail($id,$userid);
OM The Eternity
M a PHP Programmer.. And an Experienced Tester, And a Vocalist...
Updated on July 09, 2022Comments
-
OM The Eternity almost 2 years
I have a function to send mail to users and I want to pass one of its parameter as an array of ids.
Is this possible to do? If yes, how can it be done?
Suppose we have a function as:
function sendemail($id, $userid) { }
In the example,
$id
should be an array. -
Gaurav about 13 years@vickirk : I edited your answer to correct mistake of $userid. hope you don't mind?
-
Tanner Ottinger about 13 yearsNote that you don't need to define it before calling the function. you could have done:
sendemail(array("foo" => "bar"), ...)
. -
Gaurav about 13 years@Anonymous Loozah : when length of array is not too big.
-
Tanner Ottinger about 13 years@Gaurav : Yeah, but the array is probably going to be generated anyway.
-
vickirk about 13 yearsDuh, I had just been checking £/$ rates, maybe my fingers got confused when my brain was asleep. Cheers @Gaurav
-
shareef over 3 yearsThis better solution works with type safe e.g (Event ...$event)