jcropp
jcropp

Reputation: 1246

Should array_push() be used for building an array through an iterative approach in PHP?

If I wanted to build an array with pairs of data that follow a pattern like $n => myFunction($n), I think I want to do something like this:

$myArray = array();

foreach ($n as $key) {
    $new_data = array($key => myFunction($key));
    array_push($myArray, $new_data);
}

However, I’ve heard developers criticize the array_push() function, so I wonder if there is a better way to go about this.

Upvotes: 0

Views: 249

Answers (1)

GolezTrol
GolezTrol

Reputation: 116160

It's not bad per se, but function calls in PHP are relatively slow, so if you avoid array_push throughout your code, you may notice the effect. Personally I always use the [] notation, mainly because I think it's cleaner, but it's also faster.

$myArray[] = $new_data;

Even the documentation of array_push mentions this alternative as a faster one:

Note: If you use array_push() to add one element to the array it's better to use $array[] = because in that way there is no overhead of calling a function.

But there's also the advantage of array_push, you can use it to push multiple elements to an array:

array_push($myArray, 'value1', 'value2', 'value3');

So it has its uses, but for adding single elements at a time, like you do, the shorter notation of $myArray[] = ... is faster.

Upvotes: 1

Related Questions