2

I have a function getPrice($_SESSION['external']);

function getPrice($position)
    {
        //Here I perform SQL functions using $position['arraykey']
        //This works

        //Here I want to add to the array
        //This doesn't work
        $position[0]['pricing'] = $sql_result;
    }

When I use $position it doesn't add to the array, but when I use $_SESSION['external'] it works fine.

I'm not sure why $position works in the SQL query part of my function but one line bellow when I try to add the result to the array, it doesn't.

6
  • 1
    Can you describe what you mean by it doesn't ? Have you done any debugging ?
    – Rikesh
    Commented May 9, 2013 at 6:23
  • @Rikesh Using $position[0]['pricing'] to add to my array doesn't work. Using $_SESSION['external']['pricing'] does.
    – user1871245
    Commented May 9, 2013 at 6:25
  • Can you create a pastebin of your code snippet ?
    – Rikesh
    Commented May 9, 2013 at 6:26
  • try with $position['pricing'], else please be more specific about your array thing.. Commented May 9, 2013 at 6:29
  • 1
    You need to return your resultant array.
    – Rikesh
    Commented May 9, 2013 at 6:35

1 Answer 1

1

You have to pass the $position variable by reference Like below:

function getPrice(&$position)
    {
        //Here I perform SQL functions using $position['arraykey']
        //This works

        //Here I want to add to the array
        //This doesn't work
        $position[0]['pricing'] = $sql_result;
    }
5
  • Ah yes! Thank you very much, wasn't aware of passing by reference. Works perfectly.
    – user1871245
    Commented May 9, 2013 at 6:39
  • 1
    @MichaelN Btw, it's not recommended to modify your function parameters; consider returning the modified variable instead.
    – Ja͢ck
    Commented May 9, 2013 at 6:40
  • @Jack Why isn't it recommended? I'll look into returning as well. Thanks.
    – user1871245
    Commented May 9, 2013 at 6:42
  • 1
    @MichaelN 1. because of the function name and 2. because immutable design is generally better for stability.
    – Ja͢ck
    Commented May 9, 2013 at 6:43
  • @Jack & @ Michael N: yes, it is better way to return from function instead of modifying function parameter.
    – Hrishi
    Commented May 9, 2013 at 9:10

Your Answer

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