Sending array to php function
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.]
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».
*/
?>
Sending array to php function
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.]
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».
*/
?>
Send array to function in php
Since I want to be able to call an assortment of different methods from this interface, I want a way to pass parameters to the functions without knowing what order they need to be in. I would like to send different array values with various different submit buttons all within one element.
Send array to function in php
function dosomething () < . do something with the array. like print value ! >$ar = array(1,2,3); dosomething ($ar);
That piece of code work fine.
What i try to do is to pass the array DIRECTLY to the function i have try this, non work. HELP !
dosomething ([12,32,56]); dosomething (); dosomething ("[98,74,52]");
first you have to specify the parameter in the function:
function dosomething($array)
Then you have to pass the array and define it like you did in your code but directly in the function:
Passing PHP array into external Javascript function as, I’m doing something which I need to pass an array from my php to a function on an external javascript. I’m currently doing some test right now which looks like this: <input type=»text» onclick=»
Passing POST array to php function
Can i pass the entire POST array into a function and handle it within the function?
PostInfo($_POST); function PostInfo($_POST) < $item1 = $_POST[0]; $item2 = $_POST[1]; $item3 = $_POST[2]; //do something return $result; >
or is this the correct way of doing this?
Yes. If you are going to name the local variable $_POST though, don’t bother. $_POST is a ‘ superglobal ‘, a global that doesn’t require the global keyword to use it outside normal scope. Your above function would work without the parameter on it.
NOTE You cannot use any superglobal (i.e. $_POST ) as a function argument in PHP 5.4 or later. It will generate a Fatal error
You can actually pass $_POST to any function which takes in an array.
function process(array $request) < >process($_POST); process($_GET);
The $_POST -array is an array like every other array in PHP (besides being a so-called superglobal ), so you can pass it as a function parameter, pass it around and even change it (even though this might not be wise in most situations).
Regarding your code, I’d change it a bit to make it more clear:
PostInfo($_POST); function PostInfo($postVars) < $item1 = $postVars[0]; $item2 = $postVars[1]; $item3 = $postVars[2]; //do something return $result; >
This will visibly separate the function argument from the $_POST superglobal. Another option would be to simple remove the function argument and rely on the superglobal-abilities of $_POST :
PostInfo(); function PostInfo() < $item1 = $_POST[0]; $item2 = $_POST[1]; $item3 = $_POST[2]; //do something return $result; >
Pass php array to jquery function, I got a page with a form to fill it with custormers info. I got previous custormers data stored in a php array. With a dropdownlist users can fill the form with my stored data. what i have is a jquery function that triggers when the value changes and inside that function i whould like to update the form values with my …
Pass Associative Array to Function in PHP
I’m curious to know if there is some way to call a function using an associative array to declare the parameters.
For instance if I have this function:
Is there some way to call it doing something like this?
call('test', array('hello' => 'First value', 'world' => 'Second value'));
I’m familiar with using call_user_func and call_user_func_array , but I’m looking for something more generic that I can use to call various methods when I don’t know what parameters they are looking for ahead of time.
Edit: The reason for this is to make a single interface for an API front end. I’m accepting JSON and converting that into an array. So, I’d like different methods to be called and pass the values from the JSON input into the methods. Since I want to be able to call an assortment of different methods from this interface, I want a way to pass parameters to the functions without knowing what order they need to be in. I’m thinking using reflections will get me the results I’m looking for.
function test($assocArr)< foreach( $assocArr as $key=>$value ) < echo $key . ' ' . $value . ' '; >> test(['hello'=>'world', 'lorem'=>'ipsum']);
Also, look up token operator (. ). It is a way to use varargs with functions in PHP. You can declare something like this: —
You can use this function internal in your functions func_get_args()
So, you can use it like this one:
function test() < $arg_list = func_get_args(); echo $arg_list[0].' '.$arg_list[1]; >test('hello', 'world');
The following should work .
function test($hello, $world) < echo $hello . $world; >$callback = 'test'; 'First value', 'world' => 'Second value'); $reflection = new ReflectionFunction($callback); $new_parameters = array(); foreach ($reflection->getParameters() as $parameter) < $new_parameters[] = $parameters[$parameter->name]; > $parameters = $new_parameters; call_user_func_array($callback, $parameters);
Passing an Array as Arguments, not an Array, in PHP, Teams. Q&A for work. Connect and share knowledge within a single location that is structured and easy to search. Learn more
How to send array with various submit buttons?
Can you send an array with various values in html? I would like to send different array values with various different submit button s all within one element.
Here is what I am doing currently. It works so I’m not having a problem, but I couldn’t find any documentation for anything similar and I am really curious if theres another way.
Button with my *psuedo*array
Decode function:
$action = explode(',', $_POST['form_action']); $new = array(); foreach ($action as $v) < $t = explode(':',$v); $new[$t[0]] = $t[1]; >print_r($new);
And the results:
Array ( [action] => new_business [id] => 0 )
Of course, this works, so I’m really just curious whether there’s a built in solution already.
The desired simplicity:
'foo','1'=>'bar')"> print_r($_POST['array]); Array ( [0] => foo [1] => bar )
Edit: I know how to send arrays with html, but that was not my question. If I use hidden inputs, they get sent regardless of which submit button I click, there will be multiple submit buttons contained in one element, and I need to know which was clicked and what action it is going to be used for. Sorry if that was unclear but I don’t think I deserve downvotes either way.
Inputs with names of the form nameSending array to php function will be condensed into an array. This also applies to name[] , which will become elements of an indexed array.
I know the question is old. I still like to answer this, as I am implementing currently something similar.
You can indeed write your statement and turn it into a valid context. By implementing:
you concatenate your POST to a valid php expression in string format and evaluate it. This however is very dangerous because it allows execution of any code inside without any verification. You MUST NOT use this in a public environment because anyone can easily modify the string being send by the button.
The best solution in terms of safety and efficiency is really to send a csv format:
$my_assoc = array(); if(isset($_POST['action'])) < $my = explode(",",filter_input(INPUT_POST, 'action' , FILTER_SANITIZE_STRING)); for($i = 0, $num = count($my); $i < $num; $i+=2)< $my_assoc[$my[$i]] = $my[$i+1]; >print_r($my_assoc); >
The explode function is linear in complexity and has no large impact. By filtering the csv string, you can also make sure to have no unwanted characters in it (never trust incoming data). You can then either keep the indexed array ($my) and treat every two values as (psydo) key-value pair or turn it into an associative array ($my_assoc).
PHP how to send array variables to Class function, And indeed, you try to call the method insert () on your array. And that won’t work, since your array don’t know any method called insert (). The right call to the method would be (Not the final one. ): $dodaj = $rejestruj->insert (); Now the method call should work. But in fact, it won’t insert anything. Why?
Передать массив в функцию
Передать массив параметров в функцию
Доброго времени суток Столкнулся с такой проблемой Есть Функция: $new_image =.
Как передать переменную (массив) в функцию?
У меня с этим PHP уже реально крыша отъезжает. Я-то привык, что во всех известных мне языках.
Передать массив d JS-функцию
Здравствуйте. Есть два массива $A и $B. Нужно что бы при клике на элемент массива А, выводился.
Сообщение было отмечено Памирыч как решение
Решение
Позволю себе несколько развернуть ответ, а то я когда сам учил это дело, не сразу догнал из за одинаковых имён.
function arrayFunc($arr) { print_r($arr); } $ljuboj_massiv = array(1 => 'one', 2 => 'two'); arrayFunc($ljuboj_massiv);
Может быть лучше переменную назвать не $ljuboj_massiv, а, например $any_array или $another_array?
А то как-то не смотрится, там one, to, а здесь русский транслит. Тогда уж odin, dva.
Передать переменные в функцию
Здравствуйте. Есть сценарий: function template($tpl, $template) .
Передать параметр во вложенную функцию
как из объекта, можно передать параметр в вложенную функцию? public function fn1()< function.
Передать переменную из php в функцию js
Прошу помочь, кто разбирается. Суть есть переменная $Pobn которая получается так:$Pobn =.
передать выбранный option в функцию
привет! имеется 3 select’a,второй получает контент ответом на пост запрос исходя из первого,третий.