Reputation: 4242
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?
Upvotes: 0
Views: 342
Reputation: 1487
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]);
Upvotes: 0
Reputation: 3440
first count/check your resutl
is contain any resultset. and try using '&' in parameter of array
function GetDetailsById ($iStudentId, &$aDetailsId)
Upvotes: 0
Reputation: 522636
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) ...
Upvotes: 1
Reputation: 401182
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
function GetDetailsById ($iStudentId)
{
$result = array();
// TODO here, fill $result with your data
return $result;
}
And call the function :
$aDetailsId = $oDetailsTable->GetDetailsById("1");
Upvotes: 2