0

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?

1
  • isn't it typo : array_push($aDetailsId), $row[0]); Commented Feb 23, 2012 at 7:04

4 Answers 4

2

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");
Sign up to request clarification or add additional context in comments.

Comments

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:

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

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

Comments

0

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

function GetDetailsById ($iStudentId, &$aDetailsId)

Comments

0

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]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.