Jump to content

[SOLVED] array_push (two arrays)


malikah

Recommended Posts

array_push() is pushing the $def array in as the 4th item of the $abc array

 

so to echo a would still be $abc[0] and to echo d would be $abc[3][0]

 

Thanks Matthew, that makes sense now. Do you know a speedy function for adding each element to the beginning of the second array?

If you're looking for speedy insertion in the beginning you should look at another data structure than arrays such as a linked list. Putting something in the beginning of an array is by nature an expensive operation because you have to move all the other elements upwards.

 

See this quick benchmark for instance:

$iterations = 10000;

$start = microtime(true);
$array = array();
for ($i = 0; $i < $iterations; ++$i) {
array_unshift($array, $i);
}
echo 'Total time (array): ' . (microtime(true) - $start) . PHP_EOL;

unset($array);

$start = microtime(true);
$memory = memory_get_usage(true);
$list = new SplDoublyLinkedList();
for ($i = 0; $i < $iterations; ++$i) {
$list->unshift($i);
}
echo 'Total time (linked list): ' . (microtime(true) - $start) . PHP_EOL;

 

Total time (array): 6.3017320632935

Total time (linked list): 0.01022481918335

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.