0

I am stumped on my array is not being saved after having values added to it in the functions. I believe it is a problem with the variables not being in the scope of the function. I have the following variables:

$oldInterestIdArray = array();
$newInterestsIdArray = array();

and I have some functions to populate the arrays:

    function oldInterestIds($value, $key)
    {
        $data = fetchInterestDetail($value);
        $id = $data['id'];
        $oldInterestIdArray[] = $id;
    }


    function getNewInterestIds($value,$key)
    {
        if(interestExists($value))
        {
            $data = fetchInterestDetail($value);
            $id = $data['id'];
            $newInterestsIdArray[] = $id;
        }
        else
        {
            addInterest($value);
            $data = fetchInterestDetail($value);
            $id = $data['id'];
            $newInterestsIdArray[] = $id;
        }
    }

        if(count($errors) == 0)
        {
            $newInterests = array_diff($interestsArray, $interests);
            $common = array_intersect($interestsArray, $interests);
            $toChangeId = array_diff($interests, $common);
            array_walk($toChangeId, "oldInterestIds");
            array_walk($newInterests, "getNewInterestIds");
            echo json_encode($oldInterestIdArray);
        }

    }

But the $oldInterestIdArray is returning blank. But if I were to echo json inside the oldInterestIds function it works, which leaves me to believe this is a problem with the variables scope. I have tried changing the variable to:

global $oldInterestIdArray;
global $newInterestsIdArray;

But that is returning null. Any suggestions?

1
  • What if you return $oldInterestIdArray? Have you tried that? Commented Aug 11, 2014 at 5:08

2 Answers 2

1

declare global $oldInterestIdArray; inside the function like

  function oldInterestIds($value, $key)
    {
        global $oldInterestIdArray; // set here global;
        $data = fetchInterestDetail($value);
        $id = $data['id'];
        $oldInterestIdArray[] = $id;
    }

See Example

Sign up to request clarification or add additional context in comments.

Comments

0

Pass your array in as a reference :

function oldInterestIds(&$arr, $value, $key)
{
    $data  = fetchInterestDetail($value);
    $id    = $data['id'];
    $arr[] = $id;
}

2 Comments

I am getting Warning: Missing argument 3 for oldInterestIds() and Fatal error: [] operator not supported for strings
Right, you need to pass it in like I said :)

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.