PHP passing array variable from function - php

I try to work on an global array from a function. Here is my code:
$myArray = array();
myfunc($myArray);
var_dump($myArray);
function myfunc($myArray){
//perform some other tasks
$myArray['name']='John';
}
But didn't work. The var_dump return empty array. How can I get the array being pass up to the global?
Thank you.

You need to pass is as a reference &
Try doing this:
function myFunc(&$myArray){
//perform some other tasks
$myArray['name']='John';
}
You could also return it as such:
$myArray = array();
$myArray = myfunc($myArray);
var_dump($myArray);
function myfunc($myArray){
//perform some other tasks
$myArray['name']='John';
return $myArray;
}

brenjt answer is probably the best, however the OP asked how to access the global variable.
You could access the $myArray globally using the global keyword, but you wouldn't pass that array into the function.
$myArray = array();
myfunc($myArray);
var_dump($myArray);
function myfunc(){
global $myArray;
//perform some other tasks
$myArray['name']='John';
}
This would NOT be the best method for accessing the array. You should use the example by brenjt, but I wanted to show that this is also possible.

Related

Looking for function similar to array_map but which the same arg each time to the callback

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.

About changing the passed variable to the function

I have a function which converts a one-indexed 2d array to a 1d array.
Example:
Given array:
array(0 => array("name"=>"Roberts", "email"=>"email#email.com"));
Returned array:
array("name"=>"Roberts", "email"=>"email#email.com");
the function is like this:
function to_1d_array($array)
{
return $array[0];
}
But I want the function to change the passed variable directly returning anything. Should I user referencing or what?
Yes, change to:
function to_1d_array(&$array)
{
$array=$array[0];
}
You should be able to use pass-by-reference, like this:
function to_1d_array(&$array)
{
$array = $array[0];
}
Notice the ampersand (&) just before the $array parameter.
The PHP documentation on this topic has more information if you need it.

Returning function result into array

I am passing an array to a function and expecting the function to store values in it. Here's my code
The Function -
function GetDetailsById ($iStudentId, $aDetailsId)
{
/* SQL */
while ($row = mysql_fetch_array($result))
{
array_push($aDetailsId, $row[0]);
}
}
Usage -
$aDetailsId = array();
$oDetailsTable->GetDetailsById("1", $aDetailsId)
When I try to do
print_r($aDetailsId)
the array shows nothing. Am I doing it the right way?
Your array needs to be passed by reference to the function ; which means the function should be defined this way :
function GetDetailsById ($iStudentId, & $aDetailsId)
{
// ...
}
For more informations, see Making arguments be passed by reference
Or you could have your function return its result -- which might be better idea (looking at the code that calls the function, you immediately know what it does) :
function GetDetailsById ($iStudentId)
{
$result = array();
// TODO here, fill $result with your data
return $result;
}
And call the function :
$aDetailsId = $oDetailsTable->GetDetailsById("1");
That's because parameters are passed by value by default, meaning only the value of the variable is passed into the function, not the variable itself. Whatever you do to the value inside the function does not affect the original outside the function.
Two options:
return the modified value from the function.
Pass the parameter by reference:
function GetDetailsById ($iStudentId, &$aDetailsId) ...
first count/check your resutl is contain any resultset. and try using '&' in parameter of array
function GetDetailsById ($iStudentId, &$aDetailsId)
Please change function declaration to,
function GetDetailsById ($iStudentId, &$aDetailsId)
There is one more mistake in array_push call. Change it to,
array_push($aDetailsId, $row[0]);

Unset a variable variable

How do you unset a variable variable representing an array element?
function remove($var) {
unset($$var);
}
$x=array('a'=>1,'b'=>2);
remove('$x["a"]');
var_dump(isset($x['a']));
The code above doesn't unset the array element x['a']. I need that same remove() function to work with $_GET['ijk'].
Just use unset() or the (unset) cast.
If you want to use a function to unset, something like this would be better.
function removeMemberByKey(&$array, $key) {
unset($array[$key]);
}
It works!
You can try,
function remove(&$var,$key) {
unset($var[$key]);
}
$x=array('a'=>1,'b'=>2);
remove($x,'a');
var_dump(isset($x['a']));
Variable variables cannot be used with superglobals, so if you need it to work for $_GET as well, you need to look at using a different method.
Source: http://php.net/manual/en/language.variables.variable.php
Try This:
<?php
/* Unset All Declair PHP variable*/
$PHP_Define_Vars = array_keys(get_defined_vars());
foreach($PHP_Define_Vars as $Blast) {
// or may be reset them to empty string# ${"$var"} = "";
unset(${"$Blast"});
}
?>
unset is easier to type then remove
When using it with an array element, the array will still exist
You could rewrite your function to treat the parameter as a reference;
EDIT: updated to use alex's code
function remove(&$array, $key){
unset($array[$key]);
}
remove($x,'a');

create a variable name from a string.. php

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'

Categories