Php array to arguments list

Passing array as list of arguments to a non user defined function

I am currently writing a very basic PHP api which uses MySql databases for authentication and logging user data. I use prepared statements to avoid MySql injection. I attempted to make a generic function to handle and execute prepared queries as follows:

function query_prepared($sql, $type)//the version of PHP I am using does not support variable length arguments so I have to store all of the arguments but the sql statement and parameter types in an array ($param_args) $con = connect();//connects to the database $statement = $con->prepare($sql); if(!$statement) error("Error while querying database. " . mysqli_error($con), ERR_QUERY_DB); $statement->bind_param($type, $param_args);//bind_param($type, $var0, $var1, $var2. ) but I only have an array of $var0, $var1, $var2. so it attempts to convert my array to a string before passing it to the bind_param function. $statement->execute(); $statement->bind_result($result); $rows = array(); $i = 0; while($row = $result->fetch()) $rows[$i++] = $row; $con->close(); return $rows; > 

I have done some reading and found the call_user_func_array function but this obviously will not work in this instance. Is there any way of passing my array ($param_args) as a variable length argument to the bind_params function.

Источник

Php array to arguments list

To experiment on performance of pass-by-reference and pass-by-value, I used this script. Conclusions are below.

#!/usr/bin/php
function sum ( $array , $max ) < //For Reference, use: "&$array"
$sum = 0 ;
for ( $i = 0 ; $i < 2 ; $i ++)#$array[$i]++; //Uncomment this line to modify the array within the function.
$sum += $array [ $i ];
>
return ( $sum );
>

$max = 1E7 //10 M data points.
$data = range ( 0 , $max , 1 );

$start = microtime ( true );
for ( $x = 0 ; $x < 100 ; $x ++)$sum = sum ( $data , $max );
>
$end = microtime ( true );
echo «Time: » .( $end — $start ). » s\n» ;

/* Run times:
# PASS BY MODIFIED? Time
— ——- ——— —-
1 value no 56 us
2 reference no 58 us

3 valuue yes 129 s
4 reference yes 66 us

1. PHP is already smart about zero-copy / copy-on-write. A function call does NOT copy the data unless it needs to; the data is
only copied on write. That’s why #1 and #2 take similar times, whereas #3 takes 2 million times longer than #4.
[You never need to use &$array to ask the compiler to do a zero-copy optimisation; it can work that out for itself.]

Читайте также:  Python read json files

2. You do use &$array to tell the compiler «it is OK for the function to over-write my argument in place, I don’t need the original
any more.» This can make a huge difference to performance when we have large amounts of memory to copy.
(This is the only way it is done in C, arrays are always passed as pointers)

3. The other use of & is as a way to specify where data should be *returned*. (e.g. as used by exec() ).
(This is a C-like way of passing pointers for outputs, whereas PHP functions normally return complex types, or multiple answers
in an array)

5. Sometimes, pass by reference could be at the choice of the caller, NOT the function definitition. PHP doesn’t allow it, but it
would be meaningful for the caller to decide to pass data in as a reference. i.e. «I’m done with the variable, it’s OK to stomp
on it in memory».
*/
?>

Источник

Passing an Array as Arguments, not an Array, in PHP

I seem to remember that in PHP there is a way to pass an array as a list of arguments for a function, dereferencing the array into the standard func($arg1, $arg2) manner. But now I’m lost on how to do it. I recall the manner of passing by reference, how to «glob» incoming parameters . but not how to de-list the array into a list of arguments. It may be as simple as func(&$myArgs) , but I’m pretty sure that isn’t it. But, sadly, the php.net manual hasn’t divulged anything so far. Not that I’ve had to use this particular feature for the last year or so.

4 Answers 4

As has been mentioned, as of PHP 5.6+ you can (should!) use the . token (aka «splat operator», part of the variadic functions functionality) to easily call a function with an array of arguments:

function variadic($arg1, $arg2) < // Do stuff echo $arg1.' '.$arg2; >$array = ['Hello', 'World']; // 'Splat' the $array in the function call variadic(. $array); // => 'Hello World' 

NB: Indexed array items are mapped to arguments by their position in the array, not their keys.

Читайте также:  Shadow in css text effect

As of PHP8, and thanks to named arguments, it’s possible to use the named keys of an associative array with unpacking:

$array = [ 'arg2' => 'Hello', 'arg1' => 'World' ]; variadic(. $array); // => 'World Hello' 

As per CarlosCarucce’s comment, this form of argument unpacking is the fastest method by far in all cases. In some comparisons, it’s over 5x faster than call_user_func_array .

Aside

Because I think this is really useful (though not directly related to the question): you can type-hint the splat operator parameter in your function definition to make sure all of the passed values match a specific type.

(Just remember that doing this it MUST be the last parameter you define and that it bundles all parameters passed to the function into the array.)

This is great for making sure an array contains items of a specific type:

// Define the function. function variadic($var, SomeClass . $items) < // $items will be an array of objects of type `SomeClass` >// Then you can call. variadic('Hello', new SomeClass, new SomeClass); // or even splat both ways $items = [ new SomeClass, new SomeClass, ]; variadic('Hello', . $items); 

Источник

Is it possible to pass an array as a command line argument to a PHP script?

I’m maintaining a PHP library that is responsible for fetching and storing incoming data (POST, GET, command line arguments, etc). I’ve just fixed a bug that would not allow it to fetch array variables from POST and GET and I’m wondering whether this is also applicable to the part that deals with the command line. Can you pass an array as a command line argument to PHP?

9 Answers 9

Directly not, all arguments passed in command line are strings, but you can use query string as one argument to pass all variables with their names:

php myscript.php a[]=1&a[]=2.2&a[b]=c /* array(3) < [0]=>string(1) "1" [1]=> string(3) "2.2" ["b"]=>string(1) "c" > */ 

Strictly speaking, no. However you could pass a serialized (either using PHP’s serialize() and unserialize() or using json) array as an argument, so long as the script deserializes it.

I dont think this is ideal however, I’d suggest you think of a different way of tackling whatever problem you’re trying to address.

Читайте также:  Apache php fpm conf

As it was said you can use serialize to pass arrays and other data to command line.

shell_exec('php myScript.php '.escapeshellarg(serialize($myArray))); 
$myArray = unserialize($argv[1]); 

In case, if you are executing command line script with arguments through code then the best thing is to base encode it —

base64_encode(json_encode($arr)); 

while sending and decode it while receiving in other script.

json_decode(base64_decode($argv[1])); 

That will also solve the issue of json receiving without quotes around the keys and values. Because without quotes, it is considered to be as bad json and you will not be able to decode that.

The following code block will do it passing the array as a set of comma separated values:

php ./array_play.php 1,2,3 array(3) < [0]=>string(1) "1" [1]=> string(1) "2" [2]=> string(1) "3" > 

You need to figure out some way of encoding your array as a string. Then you can pass this string to PHP CLI as a command line argument and later decode that string.

After following the set of instructions below you can make a call like this:

To get this working you need code to execute before the script being called. I use a bash shell on linux and in my .bashrc file I set the command line interface to make the php ini flag auto_prepend_file load my command line bootstrap file (this file should be found somewhere in your php_include_path):

alias phpcl='php -d auto_prepend_file="system/bootstrap/command_line.php"' 

This means that each call from the command line will execute this file before running the script that you call. auto_prepend_file is a great way to bootstrap your system, I use it in my standard php.ini to set my final exception and error handlers at a system level. Setting this command line auto_prepend_file overrides my normal setting and I choose to just handle command line arguments so that I can set $_GET or $_POST. Here is the file I prepend:

It loops through all arguments passed and sets global variables using variable variables (note the $$). The manual page does say that variable variables doesn’t work with superglobals, but it seems to work for me with $_GET (I’m guessing it works with POST too). I choose to pass the values in as JSON. The return value of json_decode will be NULL on error, you should do error checking on the decode if you need it.

Источник

Оцените статью