Do you know that objects in PHP5 are passed by reference, while arrays and other scalar variables are passed by value? Yes, you know it, but it’s not exactly true. Let’s see some example and let’s try to answer few questions.
// depending on the machine but both lines return// expectedly equal values: 331208// 331208echomemory_get_usage();echomemory_get_usage();
// depending on the machine but both lines return
// expectedly equal values: 331208
These two lines of code, expectedly return the same value (in my case 331208), which shows us that because nothing happened in between them the memory usage isn’t growing. Let’s now put some code in between them.
If we talk about arrays and linked lists we know the pros and cons about both of them. No matter which programming language we use arrays benefit from direct access to its items, while linked lists are more memory efficient for particular tasks.
The items of a linked list keep a reference to their successor, so we can easily walk through the entire list. However we don’t have direct access to its elements. Thus we can’t go directly to its middle element! Even more – in particular implementations of a linked list we don’t know its length. But in some cases linked lists are far more effective than arrays. For instance reversing an array of non-numeric values require constant additional memory, but also requires n/2 exchanges. The same taks using linked lists is not only performed in linear time, but doesn’t require any additional memory. The only thing we need to do is to reverse the links – no movement of values and the items remain at the same place in the memory.
Merging of two arrays often require more space (proportional of the space of the two arrays) or many exchanges in case we try to do it in place. The same task on linked lists is far more effective with only changing pointers and without moving the values. Continue reading PHP: Arrays or Linked Lists?→
Although you can do this in PHP, that is completely wrong. The code becomes more difficult to read and understand. In the second place you can miss a $ sign in front of a variable declaration and thus the PHP interpreter will assume this is a string. So disable error reporting isn’t so great sometimes.