2

Is there a better syntax for this array insertion in PHP? The array already has items and I'm adding items to it. I hate that I have to repeat the array name multiple times like this

$somearray[] = "new item 1"; $somearray[] = "new item 2"; $somearray[] = "new item 3"; 
1
  • 1
    It's impossible to answer without knowing a background. Why to ask oversimplified question instead of telling a real case? Where do you get these new values from? Commented Aug 26, 2010 at 6:52

2 Answers 2

12
array_push($somearray, "new item 1", "new item 2", "new item 3"); 
Sign up to request clarification or add additional context in comments.

3 Comments

+1 Nice, didn't know array_push() accepted an arbitrary number of parameters printf()-style.
While the OP's method is still WAY readable. it is like operators in the code - horizontal positioning is a pain
@Col You can just break up the above over several lines if it's a concern. :) It greatly depends on the context though what's the most readable.
2

how about this?

array_merge($somearray, array('new item 1', 'new item 2', 'new item 3')); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.