Php writing a function with unknown parameters? - php

How would I go about writing a function in php with an unknown number of parameters, for example
function echoData (parameter1, parameter2,) {
//do something
}
But when you call the function you can use:
echoData('hello', 'hello2', 'hello3', 'hello'4);
So that more parameters can be sent as the number of parameters will be unknown.

Just for those who found this thread on Google.
In PHP 5.6 and above you can use ... to specify the unknown number of parameters:
function sum(...$numbers) {
$acc = 0;
foreach ($numbers as $n) {
$acc += $n;
}
return $acc;
}
echo sum(1, 2, 3, 4); // 10
$numbers is an array of arguments.

func_get_args()
function echoData(){
$args = func_get_args();
}
Be aware that while you can do it, you shouldn't define any arguments in the function declaration if you are going to use func_get_args() - simply because it gets very confusing if/when any of the defined arguments are omitted
Similar functions about arguments
func_get_arg()
func_get_args()
func_num_args()

use func_get_args() to retrieve an array of all parameters like that:
$args = func_get_args();
You can then use the array or iterate over it, whatever suits your use-case best.

You can also use an array:
<?php
function example($args = array())
{
if ( isset ( $args["arg1"] ) )
echo "Arg1!";
}
example(array("arg1"=>"val", "arg2"=>"val"));

Related

How to avoid a really long list of function parameters in PHP?

My problem is that I have lots of functions with VERY long lists of function parameters such as this one:
function select_items($con,$type,$id_item,$item_timestamp,$item_source_url,$item_type,$item_status,$item_blogged_status,$item_viewcount,$item_language,$item_difficulty,$item_sharecount,$item_pincount,$item_commentcount,$item_mainpage,$item_image_width,$item_image_height,$item_image_color,$item_modtime,$order,$start,$limit,$keyword,$language,$id_author,$id_sub_category,$id_category,$id_tag,$id_user){ ... }
As you can see its super long and (of course) very hard to maintain. Sometimes I need all of the variables to construct a super complex sql query, but sometimes I just use 1 or 2 of them. Is there a way to avoid this colossal list of parameters? For example with some strict / special naming convention ?
So basically I need something like this:
$strictly_the_same_param_name="It's working!";
echo hello($strictly_the_same_param_name);
function hello() //<- no, or flexible list of variables
{
return $strictly_the_same_param_name; // but still able to recognize the incoming value
}
// outputs: It's working!
I thought about using $_GLOBALs / global or $_SESSIONs to solve this problem but it doesn't seems really professional to me. Or is it?
For a first step, as you said, sometimes you need to call the function with only 2 args, you can set default values to your arguments in the declaration of your function. This will allow you to call your function with only 2 args out of 25.
For example:
function foo($mandatory_arg1, $optional_arg = null, $opt_arg2 = "blog_post") {
// do something
}
In a second step, you can use, and especially for that case, arrays, it will be way more simple:
function foo(Array $params) {
// then here test your keys / values
}
In a third step, you can also use Variable-length argument lists (search in the page "..."):
function sum(...$numbers) {
$acc = 0;
foreach ($numbers as $n) {
$acc += $n;
}
return $acc;
}
But ultimately, I think you should use objects to handle such things ;)
You can try use ... token:
$strictly_the_same_param_name= ["It's working!"];
echo hello($strictly_the_same_param_name);
function hello(...$args) //<- no, or flexible list of variables
{
if ( is_array( $args ) {
$key = array_search( 'What you need', $args );
if ( $key !== false ) {
return $args[$key];
}
}
return 'Default value or something else';
}

passing indefinite number of arguments to function without using an array

I am having situation where i want to pass variables in php function.
The number of arguments are indefinite. I have to pass in the function without using the array.
Just like normal approach. Comma Separated.
like test(argum1,argum2,argum3.....,..,,.,.,.....);
How i will call the function? Suppose i have an array array(1,2,3,4,5) containing 5 parameters. i want to call the function like func(1,2,3,4,5) . But the question is that, How i will run the loop of arguments , When calling the function. I tried func(implode(',',array)); But it is taking all return string as a one parameters
In the definition, I also want the same format.
I can pass variable number of arguments via array but i have to pass comma separated.
I have to pass comma separated. But at the time of passing i don't know the number of arguments , They are in array.
At the calling side, use call_user_func_array.
Inside the function, use func_get_args.
Since this way you're just turning an array into arguments into an array, I doubt the wisdom of this though. Either function is fine if you have an unknown number of parameters either when calling or receiving. If it's dynamic on both ends, why not just pass the array directly?!
you can use :
$function_args = func_get_args();
inside your test() function definition .
You can just define your function as
function test ()
then use the func_get_args function in php.
Then you can deal with the arguments as an array.
Example
function reverseConcat(){
return implode (" ", array_reverse(func_get_args()));
}
echo reverseConcat("World", "Hello"); // echos Hello World
If you truely want to deal with them as though they where named parameters you could do something like this.
function getDistance(){
$params = array("x1", "y1", "x2", "y2");
$args = func_get_args();
// trim excess params
if (count($args) > count($params) {
$args = array_slice(0, count($params));
} elseif (count($args) < count($params)){
// define missing parameters as empty string
$args = array_pad($args, count($params), "");
}
extract (array_combine($params, $args));
return sqrt(pow(abs($x1-$x2),2) + pow(abs($y1-$y2),2));
}
use this function:
function test() {
$args = func_get_args();
foreach ($args as $arg) {
echo "Arg: $arg\n";
}
}
I'm not sure what you mean by "same format." Do you mean same type, like they all have to be a string? Or do you mean they need to all have to meet some criteria, like if it's a list of phone numbers they need to be (ddd) ddd-dddd?
If it's the latter, you'll have just as much trouble with pre-defined arguments, so I'll assume you mean you want them all to be the same type.
So, going off of the already suggested solution of using func_get_args(), I would also apply array_filter() to ensure the type:
function set_names() {
function string_only($arg) {
return(is_string($arg));
}
$names_provided = func_get_args();
// Now you have an array of the args provided
$names_provided_clean = array_filter($names_provided, "string_only");
// This pulls out any non-string args
$names = array_values($names_provided_clean);
// Because array_filter doesn't reindex, this will reset numbering for array.
foreach($names as $name) {
echo $name;
echo PHP_EOL;
}
}
set_names("Joe", "Bill", 45, array(1,2,3), "Jane");
Notice that I don't do any deeper sanity-checks, so there could be issues if no values are passed in, etc.
You can use array also using explode http://www.php.net/manual/en/function.explode.php.
$separator = ",";
$prepareArray = explode ( $separator , '$argum1,$argum2,$argum3');
but be careful, $argum1,$argum2, etc should not contain , in value. You can overcome this by adding any separator. $separator = "VeryUniqueSeparator";
I don't have code so can't tell exact code. But manipulating this will work as your requirements.

Confused on PHP func_num_args() Function

Following a Tutorial I am struggling with an issue in a PHP function. I have some basic background on C# and Java and according to my knowledge this code shouldn't work since I am not passing any parameter in the add() function, but , surprisingly!, it works!
According to PHP Manual the func_num_args() Gets the number of arguments passed to the function.so how we can echo the result of the add() function while we are not passing any parameter in the function?! Also, if the function is for getting the number of arguments how we can use it to calculate the numbers?!
<?php
function add(){
$args = func_num_args();
$sum = 0;
$i = 0;
for($i; $i< $args; $i++ ){
is_int(func_num_args($i)) ? $sum+= func_num_args($i) : die('Use Only Numbers');
}
}
echo add(2,5,10,12);
?>
Thanks for your comments
Use func_get_args():
function add(){
if(!func_num_args())return 0;
$args = func_get_args();
$sum = 0;
foreach($args as $arg){
if(is_int($arg)){
$sum += $arg;
} else {
die('Use Only Numbers');
}
}
return $sum;
}
As I mentioned in comments for "no args" case:
func_num_args()s return value is 0. for-loop in your code will not work as of $i < $args simplifies to 0 < 0, which is false.
To prevet that, you may try to use:
if(!func_num_args()){
die('There are no args!');
}
Your line echo add(); will work anyway, because:
PHP has support for variable-length argument lists in user-defined
functions. This is really quite easy, using the func_num_args(),
func_get_arg(), and func_get_args() functions.
No special syntax is required, and argument lists may still be
explicitly provided with function definitions and will behave as
normal.
Use func_get_args()
func_num_args()s return value is 0. for-loop in your code will not work as of $i < $args simplifies to 0 < 0, which is false.
To prevet that, you may try to use:
if(!func_num_args()){
die('There are no args!');
}
I think you are confused because you know what function overloading is, but php does not support function overloading in this manner.
Please go through this link. It will really help you out of your confusion.
php function overloading

PHP - Pass array as variable-length argument list

I have really simple problem in my PHP script. There is a function defined which takes variable length argument list:
function foo() {
// func_get_args() and similar stuff here
}
When I call it like this, it works just fine:
foo("hello", "world");
However, I have my variables in the array and I need to pass them "separately" as single arguments to the function. For example:
$my_args = array("hello", "world");
foo(do_some_stuff($my_args));
Is there any do_some_stuff function which splits the arguments for me so I can pass them to the function?
Use
ReflectionFunction::invokeArgs(array $args)
or
call_user_func_array( callback $callback, array $param_arr)
Well you need call_user_func_array
call_user_func_array('foo', $my_args);
http://php.net/manual/en/function.call-user-func-array.php
You are searching for call_user_func_array().
http://it2.php.net/manual/en/function.call-user-func-array.php
Usage:
$my_args = array("hello", "world");
call_user_func_array('foo', $my_args);
// Equivalent to:
foo("hello", "world");
Sounds to me like you are looking for call_user_func_array.
http://www.php.net/manual/en/functions.arguments.php#functions.variable-arg-list
Isn't this what you want?
edit
ah... ok... how about this:
Passing an Array as Arguments, not an Array, in PHP
If you can change the code of foo() it should be easy to solve this in just one place.
function foo()
{
$args = func_get_args();
if(count($args) == 1 && is_array($args[0]))
{
$args = $args[0]
}
// use $args as normal
}
This solution is not recommended at all, but just showing a possibility :
Using eval
eval ( "foo('" . implode("', '", $args_array) . "' )" );
I know it's an old question but it still comes up as the first search result - so here is an easier way;
<?php
function add(... $numbers) {
$result=0;
foreach($numbers as $number){
$result+=intval($number);
}
return $result;
}
echo add(...[1, 2])."\n";
$a = [1, 2];
echo add(...$a);
?>
Source:
https://www.php.net/manual/en/functions.arguments.php#example-142

Create PHP function that takes function as a parameter

I am trying to create a PHP function that takes another PHP function as input. Here is an example:
function getMean(function){
$allUsers = getAllUsers();
$sum = 0;
foreach ($allUsers as $currentUser ){
$sum =+ (function($currentUser['CONSUMER_ID'], 5, 8))/(8-5);
}
}
Perhaps something like this should do it. PHP has a "type" called callback, which can be a closure (as of PHP 5.3), name of a function or array containing object and the method to call. These callbacks can be called with call_user_func()
function getMean($callback){
$allUsers = getAllUsers();
$sum = 0;
foreach ($allUsers as $currentUser ){
$sum =+ (call_user_func($callback, $currentUser['CONSUMER_ID'], 5, 8))/(8-5);
}
return $sum;
}
You need PHP 5.3 to do that natively.
function getMean($function){
$allUsers = getAllUsers();
$sum = 0;
foreach ($allUsers as $currentUser ){
$sum += ($function($currentUser['CONSUMER_ID'], 5, 8))/(8-5);
}
return $sum;
}
getMean(function($consumer_id, $five, $eight) {
return $consumer_id;
});
I you run PHP 5.3- (lower than 5.3), you need to use a callback (documentation is here) along with the call_user_func() or call_user_func_array() function.
you can do that as long as function($currentUser['CONSUMER_ID'], 5, 8) returns something
It looks like the PHP Eval function is what you are looking for. Pass the getMean function a string, and then change the line to have $sum =+ (eval($param) .....)
Security is a problem though because any function can be passed.
Save the function as a variable.
$function = function($param1){ //code here }
and pass it to your other function as a parameter.
function getMean($function)
{
//code here
$sum += $function($param);
}
[edit]
PHP.net Manual - Variable Functions
are you searching for anonymous functions?
Felix
If you want to dynamically create a function in php < 5.3 then youre stuck with using create_function. Becuase of how you use this function its really insane to use it for anything but but creating simple function for array_map,array_walk or things that do simple calculations or basic text processing.
If youre doing anything more complex than that its much easier and less of a headache to simply define the function as normal and then use it with call_user_func or call_user_func_array as others have suggested.
DO NOT USE eval :-)

Categories