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?

Link to comment
Share on other sites

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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.