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.
Related
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';
}
As someone who is learning PHP I was experimenting with the arrap_map function. I was hoping that it would pass the same 3rd arg each time through to the called function. As below, this is not the behaviour of array_map. Is there an alternative function I can use to achieve this?
$arr = [['a'], ['b'], ['c']];
$args = ['set'];
function mapper($item, $arg){
return $item[] = $arg;
}
$result = array_map('mapper', $arr, $args);
only the first element has 'set' as a value
$arr = [['a'], ['b'], ['c']];
$args = ['set', 'set', 'set'];
function mapper($item, $arg){
return $item[] = $arg;
}
$result = array_map('mapper', $arr, $args);
all three elements have 'set' as a value
Your code is incorrect, $a[$b] doesn't make any sense. Both variables are strings.
Your output also doesn't make sense, quoting from the manual:
If more than one argument is passed then the returned array always has
integer keys.
To answer your question, it's a language design choice.
It could
pass NULL for missing elements (that was PHP does).
throw an error if the inputs don't have the same size.
cycle the smaller inputs.
All these have valid applications and their own problems.
I have an array and I need to pass each element of the array as parameters to a function.
Say:
$var = array("var2","var3","var4");
//Pass each element as a new parameter to a function
call_to_function ($var2, $var3, $var4);
//However, if the number of array element change it can be
$var = array("var2","var3");
call_to_function ($var2,$var3);
The problem here is, how to build dynamic number of parameters and call the function.
Use:
PHP Function mysqli_stmt::bind_param, takes multiple parameters. And I need to derive the parameters from an arrray.
Is there any way to do it?
This should work for you:
First you need to create an array with references to the corresponding variables. You can simply do this with a foreach loop like below:
foreach($var as $v) {
$bindValues[] = &$$v;
}
After this you can use call_user_func_array() to call the function to bind the variables. Here it depends if you use procedural or OOP style:
procedural:
call_user_func_array("mysqli_stmt_bind_param", array_merge([$stmt, $types], $bindValues));
OOP:
call_user_func_array([$stmt, "bind_param"], array_merge([$types], $bindValues));
You can use eval() to call the function with dynamic number of parameters.
// Construct the parameter string like "$var[0], $var[1], $var[2]"
$param_str = '';
foreach($var as $key => $val) {
$param_str .= '$var['.$key.'],';
}
$param_str = rtrim($param_str, ',');
eval('call_to_function('.$param_str.');');
Usage of eval() is not considered good practice but if your are sure that your array keys $var are always integer (like in your example default keys) then this should be good to go.
call_user_func_array() is just for that:
call_user_func_array(array($stmt, 'bind_param'), $var);
In short, I have a function like the following:
function plus($x, $y){
echo $x+$y;
}
I want to tell the function its parameters as array like the following:
$parms = array(20,10);
plus($parms);
But unfortunately, not work.
I'm tired by using another way as the following:
$parms = array(20,10);
$func_params = implode(',', $parms);
plus($func_params);
And also not work, and gives me Error message:
Warning: Missing argument 2 for plus(), called in.....
And now, I'm at a puzzled.
What can I do to work ?
There is a couple things you can do.
Firstly, to maintain your function definition you can use call_user_func_array(). I think this is ugly.
call_user_func_array('plus', $parms);
You can make your function more robust by taking a variable number of params:
function plus(){
$args = func_get_args();
return $args[0] + $args[1];
}
You can simply accept an array and add everything up:
function plus($args){
return $args[0] + $args[1];
}
Or you could sum up all arguments:
function plus($args){
return array_sum($args);
}
This is PHP, there are 10 ways to do everything.
You need to adapt your function so that it only accepts one parameter and then in the function itself, you can process that parameter:
Very simple example:
function plus($arr){
echo $arr[0]+$arr[1];
}
$parms = array(20,10);
plus($parms);
You can easily adapt that to loop through all elements, check the input, etc.
Heh? The error message is very clear: you ask for two parameters in your function, but you only provide one.
If you want to pass an array, it would be a single variable.
function plus($array){
echo ($array[0]+$array[1]);
}
$test = array(1,5);
plus($test); //echoes 6
Use this:
function plus($arr){
$c = $arr[0]+$arr[1];
echo $c;
}
And the you can invoke:
$parms = array(20,10);
plus($parms);
I have this recursive function in which I must use an array for memory and verification of used data, meaning, after a string has been used i would like to remember that it has been used so i will not go over that string again in the next iteration.
The problem is after the first iteration the array is considered NULL.
So my question is this : How do i pass an array in a recursive function ? or how do i work with arrays in recursive function?
I looked this up here and though there are many similar questions none answer my one.
Note: I understand that anything that can be done with recursion can be done with a loop... yet... this is the function. And like i mentioned on the 2nd iteration the array is considered to be NULL and i get this warning:
array_push() expects parameter 1 to be array, null given in...
Here is the logic of the function:
// Set Vars...
$Str = 'someData';
$S_Array = array();
// initial call...
GetData($Str, $S_Array);
function GetData ($string, $array)
{
// string manipulations code...
.
.
.
.
// Attempt to Store in array
array_push($array, $string);
foreach ($array as $val) {
// Recursive Call...
GetData($val, $array);
}
}
You are using array_push wrong -- the order of the arguments is switched. And there's really no need to use array_push at all, since the same result can be achieved with
$array[] = $string;