malikah Posted July 27, 2009 Share Posted July 27, 2009 Why doesn't this work?: $abc = array("a","b","c"); $def = array("d","e","f"); array_push($abc, $def); echo $def[0]; // I THOUGHT THIS WOULD OUTPUT "a" BUT IT DOESN'T Quote Link to comment Share on other sites More sharing options...
vineld Posted July 27, 2009 Share Posted July 27, 2009 Too quick. Quote Link to comment Share on other sites More sharing options...
MatthewJ Posted July 27, 2009 Share Posted July 27, 2009 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] Quote Link to comment Share on other sites More sharing options...
malikah Posted July 27, 2009 Author Share Posted July 27, 2009 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? Quote Link to comment Share on other sites More sharing options...
corbin Posted July 27, 2009 Share Posted July 27, 2009 array_merge Quote Link to comment Share on other sites More sharing options...
malikah Posted July 27, 2009 Author Share Posted July 27, 2009 array_merge Beautiful ! Quote Link to comment Share on other sites More sharing options...
Daniel0 Posted July 27, 2009 Share Posted July 27, 2009 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 Quote Link to comment Share on other sites More sharing options...
vineld Posted July 27, 2009 Share Posted July 27, 2009 Yup but usually you wouldn't put elements at the start of an array. In this case I assume it's just about learning the basics of array functionality although I could be wrong. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.