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.
Related
I currently have a php function, in which the 1st parameter is a reference to an array and the 2nd parameter is one of its keys,
function fun(&$a, $k) {
......
}
I want to modify the function so that I just need to pass one parameter $a[$k]. Inside the function , $a can be extracted from $a[$k] and then I can call array_search($a[$k], $a) to get $k. Is that possible in PHP?
function fun(&$ak) {
// $ak is from $a[$k]
// a php utility to extract $a from $ak? ...
$k = array_search($ak, $a);
}
Short answer: No, there's no way to "extract" that information, because that information doesn't exist in the scope of your function.
Long answer:
As people have pointed out in the comments, you simply cannot do this. If you have a function like this:
function fun(&$foo) {
...
}
there is no information passed to that function about where $foo came from. It could be a standalone variable, an array element ($bar[1]), an object property ($baz->bingo), or anything else (think SomeClass::$bar->baz[$bingo->boingo]). There's no way to tell.
To verify this, try var_dump($ak); in your function; it won't contain any information about what array or object it's in (or its array index or property name). It's just like any other variable.
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.
I'm curious if I can assign a variable the value of a specific array index value returned by a function in PHP on one line.
Right now I have a function that returns an associative array and I do what I want in two lines.
$var = myFunction($param1, $param2);
$var = $var['specificIndex'];
without adding a parameter that determines what the return type is, is there a way to do this in one line?
In PHP 5.4, you can do this: $var = myFunction(param1, param2)['specificIndex'];.
Another option is to know the order of the array, and use list(). Note that list only works with numeric arrays.
For example:
function myFunction($a, $b){
// CODE
return array(12, 16);
}
list(,$b) = myFunction(1,2); // $b is now 16
You could add an additional optional parameter and, if set, would return that value. See the following code:
function myFunction($param1, $param2, $returnVal = "")
{
$arr = array();
// your code here
if ($returnVal)
{
return $arr[$returnval];
}
else
{
return $arr;
}
}
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]);
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'