0

I would like to append elements to an array that is part of another array. I add an element to $aA in this way:

$aA[] = array('label'=>"string1",'data'=>array());

By this the array will be extended by new element with the following context in json notation:

{ index:'string1',data:{}}

The array referred to by 'data' is initially empty.

A bit later I would like to append/push the elements 1,2,3 to the 'data' array in the last element of $aA. I have tried with this:

end($aA)['data'][]=1;
end($aA)['data'][]=2;
end($aA)['data'][]=3;

with the following expected content of the last element i $aA

{ index:'string1',data:{1,2,3}}

But this doesn't work. The array referred to by 'index' is still empty.

How should I do this to make it work?

4
  • Try $aA[ count( $aA ) - 1 ]['data'][] = ... instead of end($aA)... Commented Jan 17, 2020 at 16:40
  • @marekful Thanks, your proposal worked fine! Now I just wonder why end($aA) doesn't work.... Commented Jan 17, 2020 at 16:51
  • end() returns a copy of the last element in the array. Changing that will not be reflected in the original array. Commented Jan 17, 2020 at 16:53
  • Thanks, I learn day by day. This was a nasty one.... Commented Jan 17, 2020 at 18:33

1 Answer 1

1

How about you use array_push?

array_push($aA['data'], 1);

PHP: array_push

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

1 Comment

Well, see comments on my original post. The problem is not the push operation, but how I refer to the last item on the list. Probably nothing wrong with your proposal but it will not solve my problem.

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.