Difference Between Array_Push() and $Array[] =

Difference between array_push() and $array[] =

When you call a function in PHP (such as array_push()), there are overheads to the call, as PHP has to look up the function reference, find its position in memory and execute whatever code it defines.

Using $arr[] = 'some value'; does not require a function call, and implements the addition straight into the data structure. Thus, when adding a lot of data it is a lot quicker and resource-efficient to use $arr[].

What is the difference between array_push() and array_merge()?

You can refer to the PHP manual, but for now I will explain the difference like this:

array_push()

Treats the array as a stack, and pushes the passed variables onto the end of the array. The length of the array increases by the number of variables pushed.

Example

$stack = array("orange" , "banana");
array_push($stack, "1", "2");
print_r($stack);

The above example will output:

Array
(
[0] => orange
[1] => banana
[2] => 1
[3] => 2
)

array_merge()

Merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array. If the input arrays have the same string keys, then the later value for that key will overwrite the previous one.

If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended. Values in the input array with numeric keys will be renumbered with incrementing keys starting from zero in the result array.

Example

$array1 = array("color" => "yellow" , 0, 1);
$array2 = array("a" , "b" , "color" => "blue" , "shape" => "rectangle", 1);
$result = array_merge($array1 , $array2);
print_r($result);

The above example will output:

Array
(
[color] => blue
[0] => 0
[1] => 1
[2] => a
[3] => b
[shape] => rectangle
[4] => 1
)

array_push() vs. $array[] = .... Which is fastest?

You can run it and see that array_push is slower in some cases:

http://snipplr.com/view/759/speed-test-arraypush-vs-array/

Run your code. Enjoy.

Which is faster in PHP, $array[] = $value or array_push($array, $value)?

I personally feel like $array[] is cleaner to look at, and honestly splitting hairs over milliseconds is pretty irrelevant unless you plan on appending hundreds of thousands of strings to your array.

I ran this code:

$t = microtime(true);
$array = array();
for($i = 0; $i < 10000; $i++) {
$array[] = $i;
}
print microtime(true) - $t;
print '<br>';
$t = microtime(true);
$array = array();
for($i = 0; $i < 10000; $i++) {
array_push($array, $i);
}
print microtime(true) - $t;

The first method using $array[] is almost 50% faster than the second one.

Some benchmark results:

Run 1
0.0054171085357666 // array_push
0.0028800964355469 // array[]

Run 2
0.0054559707641602 // array_push
0.002892017364502 // array[]

Run 3
0.0055501461029053 // array_push
0.0028610229492188 // array[]

This shouldn't be surprising, as the PHP manual notes this:

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.

The way it is phrased I wouldn't be surprised if array_push is more efficient when adding multiple values. Out of curiosity, I did some further testing, and even for a large amount of additions, individual $array[] calls are faster than one big array_push. Interesting.

Difference between assignment and array_push in PHP in a foreach loop

If you want to use the assignment but see the same results as array_push() outside your loop, you need to assign the item as a new element in the array via:

$data['database'][] = $row;

This should produce the same results as:

array_push($data['database'], $row);

The way you have it written $data['database'] is being overwritten by $row.

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

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.

Which Is Faster $variable[] or array_push($variable, $newValue)?

http://www.php.net/manual/en/function.array-push.php#53289

Empy bracket doesn't check if a
variable is an array first as
array_push does. If array_push finds
that a variable isn't an array it
prints a Warning message if E_ALL
error reporting is on.

So array_push is safer than [], until
further this is changed by the PHP
developers.

$variable[] seems to be a lot faster:

http://www.php.net/manual/en/function.array-push.php#83388

However if you're adding multiple values per iteration array_push() is faster:

http://www.php.net/manual/en/function.array-push.php#84959

But please remember that pre-optimization is the root of all evil. Use whatever you feel more comfortable with, and when you have a performance issue, use a profiler and do some benchmarking.

What is the difference between array_push() and array_merge()?

You can refer to the PHP manual, but for now I will explain the difference like this:

array_push()

Treats the array as a stack, and pushes the passed variables onto the end of the array. The length of the array increases by the number of variables pushed.

Example

$stack = array("orange" , "banana");
array_push($stack, "1", "2");
print_r($stack);

The above example will output:

Array
(
[0] => orange
[1] => banana
[2] => 1
[3] => 2
)

array_merge()

Merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array. If the input arrays have the same string keys, then the later value for that key will overwrite the previous one.

If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended. Values in the input array with numeric keys will be renumbered with incrementing keys starting from zero in the result array.

Example

$array1 = array("color" => "yellow" , 0, 1);
$array2 = array("a" , "b" , "color" => "blue" , "shape" => "rectangle", 1);
$result = array_merge($array1 , $array2);
print_r($result);

The above example will output:

Array
(
[color] => blue
[0] => 0
[1] => 1
[2] => a
[3] => b
[shape] => rectangle
[4] => 1
)

array_push creates new arrays instead of adding

You shouldn't use array_push in this case. Use simple assignment instead. As you don't know the index of the element that you are adding, you can create the new array, set all its values and then add it to the overall array. Something like this:

foreach ($messageRepo as $oneMessage) {
$calculatedTime = $oneMessage->getTimeToLive();
$creationTime = $oneMessage->getCrdate();

$calculatedTimes = $this->androidService->renderFormat($calculatedTime);
$expiringDate = $creationTime + $calculatedTime;

$newval = array(
'Time' => key($calculatedTimes),
'Format' => current($calculatedTimes),
'Title' => $oneMessage->getMessageTitle(),
'Text' => $oneMessage->getMessageText(),
);

if (time() > $expiringDate) {
$newval['Expired'] = $expiringDate;
} else {
$newval['Expiring'] = $expiringDate;
}

$ausgabe[] = $newval;
}

PHP: array_push on multidimensional arrays and display its elements

<?php foreach($query_56 as $key=>$notes):
$each_complaints[$key]["date"] = $notes->date;
$each_complaints[$key]["text"] = $notes->corresponding_text ;
endforeach;

echo "<pre>";print_r($each_complaints);
?>
**Output :**
(
[0] => Array
(
[date] => 01-11-2014
[text] => rrrrrr
)

[1] => Array
(
[date] => 02-11-2014
[text] => fffff
)

[2] => Array
(
[date] => 03-11-2014
[text] => ddddd
)

)


Related Topics



Leave a reply



Submit