Can we pass an array as parameter in any function in PHP? - 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.

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'));

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');

Yes, you can safely pass an array as a parameter.

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);

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);

function sendemail(Array $id,$userid){ // forces $id must be an array
Some Process....
}
$ids = array(121,122,123);
sendmail($ids, $userId);

Its no different to any other variable, e.g.
function sendemail($id,$userid){
echo $arr["foo"];
}
$arr = array("foo" => "bar");
sendemail($arr, $userid);

I composed this code as an example. Hope the idea works!
<?php
$friends = array('Robert', 'Louis', 'Ferdinand');
function greetings($friends){
echo "Greetings, $friends <br>";
}
foreach ($friends as $friend) {
greetings($friend);
}
?>

I found Delcon answer helpful but I was looking for this
function sendmail($user1, $user2, $user3){
echo $user1;
echo $user2;
echo $user3;
}
$users = array('user1','user2','user3');
sendmail(...$users);

In php 5, you can also hint the type of the passed variable:
function sendemail(array $id, $userid){
//function body
}
See type hinting.

Since PHP is dynamically weakly typed, you can pass any variable to the function and the function will try to do its best with it.
Therefore, you can indeed pass arrays as parameters.

Yes, we can pass arrays to a function.
$arr = array(“a” => “first”, “b” => “second”, “c” => “third”);
function user_defined($item, $key)
{
echo $key.”-”.$item.”<br/>”;
}
array_walk($arr, ‘user_defined’);
We can find more array functions here
http://skillrow.com/array-functions-in-php-part1/

<?php
function takes_array($input)
{
echo "$input[0] + $input[1] = ", $input[0]+$input[1];
}
?>

Related

Passing an array as the parameter of a function in PHP

This is my array
$sub = array("English"=>"12","Hindi"=>"12","History"=>"12","Geography"=>"12","Mathematics"=>"12","Physics"=>"12","Chemistry"=>"12","Biology"=>"12");
Want to pass this entire array as the parameter of a function & want to sum up the marks(array values) using the function
function sum_marks($sub){--Function body--
}
I don't know if this is the proper syntax for passing an array to a function, help!!
Is this you are looking for?
$mySum = array_sum($sub);
Yes, it is the appropriate syntax for passing an array as an argument to a function.
However, you might consider adding a type declaration for the $sub argument:
function sum_marks(array $sub)
{
return array_sum($sub);
}
Type declarations allow functions to require that parameters are of a certain type at call time. If the given value is of the incorrect type, then an error is generated: in PHP 5, this will be a recoverable fatal error, while PHP 7 will throw a TypeError exception.
However, you really probably just want to use array_sum() directly.
For reference, see:
http://php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration
http://php.net/manual/en/function.array-sum.php
Try this. It will create a function that has a reference to your array. When you change the array you can call the product of the function, and it will recalculate the sum.
$array = ['English' => '12', 'Swedish' => '12'];
function arraySumCb(&$subject) {
return function () use (&$subject) {
return array_sum($subject);
};
}
$sum = arraySumCb($array);
echo $sum(); // 24
$array['Swedish'] = '15';
echo $sum(); // 27
$array['Swedish'] = '10';
echo $sum(); // 22
Edit: This is how I would do it.
$array = ['English' => '12', 'Swedish' => '12'];
class SumMarks {
private $_subject;
public function __construct(array &$subject = []) {
$this->_subject = &$subject;
}
public function __toString() {
return "" . array_sum($this->_subject);
}
}
$sum = new SumMarks($array);
echo $sum; // 24
$array['Swedish'] = '10';
echo $sum; // 22
Edit: Proper use of PHP anonymous functions
I dont understand your question, please ask with specific question. .
But maybe this what are you want :
function sum_marks($sub){
$result = array_sum($sub);
retrun $result;
}

array_search wrong argument datatype

I am playing around with this:
$sort = array('t1','t2');
function test($e){
echo array_search($e,$sort);
}
test('t1');
and get this error:
Warning: array_search(): Wrong datatype for second argument on line 4
if I call it without function like this, I got the result 0;
echo array_search('t1',$sort);
What goes wrong here?? thanks for help.
Variables in PHP have function scope. The variable $sort is not available in your function test, because you have not passed it in. You'll have to pass it into the function as a parameter as well, or define it inside the function.
You can also use the global keyword, but it is really not recommended. Pass data explictly.
You must pass the array as a parameter! Because the functions variables are different from globals in php!
Here is the fixed one:
$sort = array('t1','t2');
function test($e,$sort){
echo array_search($e,$sort);
}
test('t2',$sort);
You cannot directly access global variables from inside functions.
You have three options:
function test($e) {
global $sort;
echo array_search($e, $sort);
}
function test($e) {
echo array_search($e, $GLOBALS['sort']);
}
function test($e, $sort) {
echo array_search($e, $sort);
} // call with test('t1', $sort);
take the $sort inside the function or pass $sort as parameter to function test()..
For e.g.
function test($e){
$sort = array('t1','t2');
echo array_search($e,$sort);
}
test('t1');
----- OR -----
$sort = array('t1','t2');
function test($e,$sort){
echo array_search($e,$sort);
}
test('t1',$sort);

How to avoid the php function call when passing a function variable?

I have a function variable like this...
$aName = "My Name";
The function need to pass in like this:
$sayHelloFunction = function sayHello($aName){
echo($aName);
}
Than, I have a method that responsible for execute the sayHelloFunction:
runningFunction($sayHelloFunction($aName));
in the runningFunction, it will have some condition to execute the function, but when I pass the "$sayHelloFunction($aName)" to runningFunction, it execute automatically, but I would like to pass the variable $aName as well, how can I achieve it? Thank you.
runningFunction($sayHelloFunction, $aName);
Simples.
You will have to pass the arguments separately. However, you could wrap them in an array so that you can pass them to runningFunction as a single argument, like this:
$printFunction = function($args) {
print $args['lastname'].', '.$args['firstname'];
};
function runningFunction($f, $a) {
$f($a);
}
$firstname = 'Bob';
$lastname = 'Smith';
$functionArguments = array(
'firstname' => $firstname,
'lastname' => $lastname
);
runningFunction($printFunction, $functionArguments);
If you want your dynamic functions to get "proper" arguments, then I see no way around something like this:
function runningFunction($f, $a) {
switch(count($a)) {
0: $f(); break;
1: $f($a[0]); break;
2: $f($a[0], $a[1]); break;
3: $f($a[0], $a[1], $a[2]); break;
// and so on
}
}
Pass the parameters as an array, and then use call_user_func_array() to call your function.
This way your runningFunction() will be absolutely abstract (as you requested), it can call any type of function, it's your responsibility to pass the right number of parameters.
function runningFunction ($callback, $parameters=array()) {
call_user_func_array($callback, $parameters);
}
runningFunction($sayHelloFunction, array($aName));
call_user_func_array()
as xconspirisist suggested pass $aName as a seperate parameter to the function.
Details on Variable Functions can be found on the PHP site.
Use an anonymous function when calling runningFunction
function runningFunction($func) {
$func();
}
runningFunction(function() {
$sayHelloFunction($aName));
// You can do more function calls here...
});

php function parameters

How to write a php function in order to pass parameters
like this
student('name=Nick&roll=1234');
If your format is URL encoded you can use parse_str to get the variables in your functions scope:
function student($args)
{
parse_str($args);
echo $name;
echo $roll;
}
Although, if this string is the scripts URL parameters you can just use the $_GET global variable.
Pass parameters like this:
student($parameter1, $parameter2){
//do stuff
return $something;
}
call function like this:
student($_GET['name'], $_GET['roll']);
Use parse_str.
function foo($paraString){
try{
$expressions = explode('&',$paraString);
$args = array();
foreach($expressions as $exoression){
$kvPair = explode('=',$exoression);
if(count($kvPair !=2))throw new Exception("format exception....");
$args[$kvPair[0]] = $kvPair[1];
}
....
Edit: that wayyou can do it manually. If you just want to get something out of a querrystring there are already functions to get the job done

How to determine user defined function parameters names before calling it?

In PHP, I have created a user defined function. Example:
<?php
function test($one, $two) {
// do things
}
?>
I would like to find the names of the function parameters. How would I go about doing this?
This is an example of what I would like:
<?php
function test($one, $two) {
// do things
}
$params = magic_parameter_finding_function('test');
print_r($params);
?>
This would output:
Array
(
[0] => one
[1] => two
)
Also this is very important that I am able to get the user defined function parameter names outside the scope of the function. Thanks in advance!
You can do this using reflection...
$reflector = new ReflectionFunction('test');
$params = array();
foreach ($reflector->getParameters() as $param) {
$params[] = $param->name;
}
print_r($params);
you can use count_parameter a php built in function

Categories