skos
skos

Reputation: 4242

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?

Upvotes: 0

Views: 342

Answers (4)

biztiger
biztiger

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

Nikson Kanti Paul
Nikson Kanti Paul

Reputation: 3440

first count/check your resutl is contain any resultset. and try using '&' in parameter of array

function GetDetailsById ($iStudentId, &$aDetailsId)

Upvotes: 0

deceze
deceze

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:

  1. return the modified value from the function.
  2. Pass the parameter by reference:

    function GetDetailsById ($iStudentId, &$aDetailsId) ...
    

Upvotes: 1

Pascal MARTIN
Pascal MARTIN

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


Or you could have your function [**return its result**][2] -- 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");

Upvotes: 2

Related Questions