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);
Related
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 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.
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;
Generally I pass an array of parameters to my functions.
function do_something($parameters) {}
To access those parameters I have to use: $parameters['param1']
What I would like to do, is run some sort of logic inside this function on those parameters that converts that array into normal variables. My main reasons is just that sometimes I have to pass a whole load of parameters and having to type $parameters['..'] is a pain.
foreach($parameters as $key=>$paremeter) {
"$key" = $parameter;
}
I thought that might work.. but no cigar!
Use extract():
function do_something($parameters) {
extract($parameters);
// Do stuff; for example, echo one of the parameters
if (isset($param1)) {
echo "param1 = $param1";
}
}
do_something(array('param1' => 'foo'));
Try $$key=$parameter.
Just extract the variables from array using extract:
Import variables into the current
symbol table from an array
extract($parameters);
Now you can access the variables directly eg $var which are keys present in the array.
There is the extract function. This is what you want.
$array = array('a'=>'dog', 'b'=>'cat');
extract($array);
echo $a; //'dog'
echo $b; //'cat'
Is it possible to sanitize all input sent by one method in PHP by simply doing
$var = mysql_real_escape_string($_POST);
and then access elements of $var as I would have of $_POST ?
I don't think you can call mysql_real_escape_string on an array.
But this would work
$cleanData = array_map('mysql_real_escape_string', $_POST);
array_map works by calling the function named in quotes on every element of the array passed to it and returns a new array as the result.
Like superUntitled, I prefer to have a custom function that uses the built-in sanitizing functions as appropriate. But you could still use a custom function with array_map to achieve the same result.
As a side note, I would recommend using a function to sanitize your results:
function escape($txt) {
if (get_magic_quotes_gpc())
$txt = stripslashes($txt);
if (!is_numeric($txt))
$txt = "'" . mysql_real_escape_string($txt) . "'";
return $txt;
}
this function will remove html tags from anything you pass to it
function strip_html(&$a){
if(is_array($a)){
foreach($a as $k=>$v){
$a[$k]=preg_replace('/<[^<]+?>/','',$v);
}
}else{
$a=preg_replace('/<[^<]+?>/','',$a);
}
return;
}
What I find handy is to encapsulate the request data (Post, Get, Cookie etc) in to an Object and then to add a filter method which u can pass an array of function names to. This way you can use it like this:
$array = array('trim','mysql_real_escape_string');
$request->filter($array);
Body of the method works using a loop an array_map like in Mark's example. I wouldn't run the mysql_real_escape_string over my entire $_POST though, only on the necessary fields ( the ones that are getting queried or inserted )
#Shadow:
Array_Map will work with single dimension array but it wont work with multi-dimension arrays.
So, this will work.
$cleanData = array_map('mysql_real_escape_string', $_POST);
but if that $_POST array were to have another array, like this:
$array = $_POST['myArray']['secondArray'];
If you have an array such as above, array map will throw an error when you try to run a function that only takes a String as an argument, because it wont be handle to an array when its expecting just a string.
The solution provided on the below page is much more handy, and does it recursively for every element inside the array.
PHP -Sanitize values of a array