19

I'm having difficulty adding to the end of an array. Not sure how to do it. Please help.

$person = array();
$person = array("name"=>"tom", "age"=>20, "height"=>180);

How do I add to the end of an array? I want to add "weight"=>120 to the end of an existing array.

Thanks

1
  • There's no such thing as the "end of an array" for an associative array. If you start thinking there is, you will be in Trouble, with a capital T. Commented Dec 31, 2015 at 7:24

1 Answer 1

40

Since this is an associative array, just do:

$person['weight']=120;

For regular numerically indexed arrays, you can use array_push() or $person []= "new value";.

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

4 Comments

even though it is associative, when used inside foreach loops the order might be important.
@amosrivera, it better not be! You absolutely should not depend on the order of keys in an associative array. In any case, this should add it to the "end", but you can test to make sure.
For regular numerically indexed arrays, you can also do $person[]="new value";
@Brad why not? PHP arrays preserver order as far as I'm aware. Plus isn't all arrays in PHP associative arrays?

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.