Here’s an array in Java:
int[] myArray = new int[3];
myArray[0] = 0;
myArray[1] = 1;
myArray[2] = 2;
The first line immediately reserves 3 consecutive blocks of memory. Creating a fourth element would actually require creating a new array with int[4], and then transferring values from index 0 to 2 into the new array. Such as the following:
int[] mySecondArray = new int[4];
for (int i = 0; i < myArray.length; i += 1) {
mySecondArray[i] = myArray[i];
}
mySecondArray[3] = 3;
But in PHP, we can declare an array, and simply add another element without all the fuss that a Java requires.
$my_array = array(0, 1, 2);
$my_array[] = 4;
Does PHP actually take care of creating a new array after pushing an additional element onto an existing array? Or are PHP arrays actually not the same (in terms of memory) as arrays in languages such as C and Java? I’m a little concerned, because I see a lot of PHP code that iterates through a loop and appends 50+ new elements onto an existing array, which would be utterly ridiculous to do in Java.
In PHP arrays are in fact hash tables. However, the memory management is hardly comparable, because they are two completely different languages.