Is there something like JavaScript's apply function in PHP? - php

In JavaScript, I can use apply to pass an array as arguments to a function:
var f = function (n,m) {},
args = [1,2];
f.apply(null, args);
I now need to do something similar in PHP i.e. pass an array of items as 'separate' arguments to a function.
Is there any way this can be done?

You can use the function call_user_func_array. Simply pass in your function (as a callback, usually a string with the function name), and an array of arguments.
Additional note: for static functions, use forward_static_call_array.

Related

How to apply a function with multiple arguments to every element of an array in PHP?

I have a method MyClass#foo(array $array, $argX, $argY, $argZ) and want to apply it to every element of $myArray.
I've tried this with array_map(...) and array_walk(...), but they are not flexible enough for a function with a custom signature.
How to apply a method with multiple arguments to every element of an array in PHP (without for iterate with a loop)?
You can use an anonymous function (maybe in combination with the use keyword to have access to the $arg* variables):
array_map(function($item) use ($argX, $argY, $argZ) {
return MyClass::foo($item, $argX, $argY, $argZ);
}, $your_array_here);
If you're running PHP 5.3+, then you can pass an anonymous function (or closure) as the callback parameter to array_map.
$newArray = array_map(function($val){
// Whatever code you want using `$val`.
// Make sure to `return` a value, though.
}, $myArray);
If you want to use other variables inside the anonymous function, then you can use the use keyword to capture them.
$newArray = array_map(function($val) use($argX, $argY, $argZ){
// Whatever code you want using `$val`,
// and also `$argX`, `$argY`, `$argZ`.
// Make sure to `return` a value, though.
}, $myArray);
Docs: http://php.net/manual/en/functions.anonymous.php

How to dynamically call PHP method and pass multiple variables not in an array?

I want to be able to call a php function, but only if the number of elements input, matches the number of elements accepted by the function and if it does match i want to pass them 1 by 1 and not as an array.
Currently i have the following code which does the job, but is messy.
call_user_func($functionname, $vars);
This was hitting problems when i had a function that expected an array of 4 elements, but was only passed 3. Having to check and make sure all the vars exist makes writing functions a bit messy. I have a better solution based on reflection. how to dynamically check number of arguments of a function in php , but im one final step short. If the number of arguments matches the number of arguments in a function, i can call that method, but i dont know how to call that method correctly. I have an array of variables. I need to pass these into the function so that I can do something like the following.
function foo($var1, $var2, $var3)
{
//I know all 3 vars exist and dont need to verify first
}
if(count($arrayof3elements) == get_method_var_count("foo") {
dynamically_call_method("foo", $arrayof3elements);
}
Instead of using call_user_func, use call_user_func_array - this allows you to pass an array of arguments, but passes them to the method as separate things.
function x($foo, $bar) {
echo $foo . $bar;
}
call_user_func_array('x', ['abc', 'def']); // prints abcdef

PHP array element calling a function?! $a=$b['c']($d,$e,$f);

Could someone please explain what is going on here in this code?
I can see it is an array called b accessing an element with the key 'c', but the stuff in the brackets? I don't know what is going on here.
$a=$b['c']($d,$e,$f);
$b['c'] must be a function name.
try to print it, you'll see.
$a=$b['c']($d,$e,$f);
calls that function passing $d, $e and $f arguments to it.
Try :
<?php
$func = 'var_dump';
$foo = array(1,2,3);
$func($foo)
It looks like you are looking at a variable function.
The expression above first evaluates the associative array $a=$b['c'] and then calls the function with that name, passing the arguments $d,$e,$f.
From the description:
PHP supports the concept of variable functions. This means that if a
variable name has parentheses appended to it, PHP will look for a
function with the same name as whatever the variable evaluates to, and
will attempt to execute it. Among other things, this can be used to
implement callbacks, function tables, and so forth.
It seems element at key c is expected to be a function.
In PHP5, you can use this kind of short notations. The function will be called with parameters d e and f.

php: the best practice to pass two global arrays to the function to modify them

There are two arrays that need to be changed within a function.
How to pass that arrays?
The way I know is to declare 2 arrays as global variables within a function:
function myfunc(){
global $arr1;
global $arr2;
//do something
}
Does it make sense and is it possible to pass two arrays as references instead? How (in case if Yes)?
Here is how you can pass them by reference, define your function as follows:
function myfunc(&$arr1, &$arr2) {
// ... modify arrays here
}
Just prepend the function arguments you want passed by reference with an &. Now when they are received by the function, they are references.
You do not have to (and should not) put the & in front of the variables when you are calling the function as this results in a call-time pass-by-reference notice. Just pass them to your function as usual $res = myfunc($first, $second);
See Passing by Reference
Yes, you can pass the arrays as reference, and that would be preferable to using globals.
function myfunc( array &$arr1, array &$arr2 ) {
// do something
}
myfunc( $someArray, $someOtherArray );
The & in the function definition tells PHP to pass a reference rather than a value.
I would take another approach (if the arrays are not too big...) to make it clear where the function is called that the original arrays will be changed (although I probably would never changed two global arrays in one function...):
function call:
list($array1, $array2) = myfunc($array1, $array2);
function:
function myfunc($array_x, $array_y){
//do something
return array($array_x, $array_y);
}

How to call a function with a variable number of parameters which correspond to an array values?

OK, I know it sounds weird but I need to make a function that will receive two parameters the first one is a string and the second an array (containing strings).
This function will then call sprintf. My first parameter will be $format and my array will correspond to the various $args.
How can I achieve this (if possible)?
Thanks!
Well you want the vsprintf() function.
Like Orbling answered, for this particular case you need vsprintf.
But, in a generic case, to call a function with variable number of parameters, you can use func_get_args() inside the function which you desire to accept multiple (any number of variable arguments). This function (when called inside your function) returns an array containing all the parameters passed while calling your function.

Categories