Reputation: 105
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?
Upvotes: 0
Views: 81
Reputation: 77966
Pass your array in as a reference :
function oldInterestIds(&$arr, $value, $key)
{
$data = fetchInterestDetail($value);
$id = $data['id'];
$arr[] = $id;
}
Upvotes: 0
Reputation: 9635
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
Upvotes: 1