Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we pass an array as parameter in any function in PHP?

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.

like image 333
OM The Eternity Avatar asked Mar 28 '11 13:03

OM The Eternity


People also ask

Can I pass an array to a function in PHP?

This tutorial explains how to pass an array as an argument in a function with PHP. The process of passing an array into a function is very much the same as passing a variable into a function.

Can we pass array as a parameter of function?

Just like normal variables, simple arrays can also be passed to a function as an argument, but in C/C++ whenever we pass an array as a function argument then it is always treated as a pointer by a function.

Can an array be passed to function as a parameter or return?

A whole array cannot be passed as an argument to a function in C++. You can, however, pass a pointer to an array without an index by specifying the array's name.

Can arrays are passed as parameters to a function either by value or by reference?

Answer: An array can be passed to a function by value by declaring in the called function the array name with square brackets ( [ and ] ) attached to the end. When calling the function, simply pass the address of the array (that is, the array's name) to the called function.


1 Answers

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')); 
like image 57
alex Avatar answered Sep 21 '22 16:09

alex