Do you really know what arrays are?

Where I work, I expect PHP and JavaScript knowledge from web developers. During the interviews, I found that it is enough to ask just one simple question to find out how deeply the developer understands the tools that he uses every day. This question is:

What are the similarities and differences between arrays in JavaScript and in PHP?

The ability to write code is one thing. And quite another - an understanding of the internal mechanisms of the languages ​​used. The answer to this single question gives me a whole sea of ​​information about the interviewee. Indeed, almost every common language has arrays. It is easy to make an assumption according to which arrays in different languages ​​are, more or less, the same thing. Many programmers do this.





This is an incorrect assumption, leading to many small errors, to writing irrationally arranged code, to the inability to effectively use the strengths of the language.

Arrays and their native language - C


The C language is not the first programming language in history, but it is the language that has influenced the IT industry more than others. Many developers taught at C institutes as their first language. Both PHP and JavaScript took something from C. As a result, we can observe some similarities between these languages ​​and C, and it is the analysis of arrays in C that will allow us to show how far these data structures have advanced since 1972.

In C, arrays are strongly typed and have a fixed length.

int myArray[10];
int fibonacci[10] = {0, 1, 1, 2, 3, 5, 8, 13, 21, 34};

Above is a couple of array declarations. They can only store integers, the number of which does not exceed 10.

When working with such arrays, a loop is used for. This pattern, without any real need, is copied in many other programming languages:

int i, sum;
for (i = 0; i < 9; i++) {
  sum += fibonacci[i];
}

Such a design does not look wild in either JavaScript or PHP. But this is where the danger lies.

JavaScript arrays


You can imagine that arrays in JavaScript are very similar to arrays in C. And the truth is that the following constructions look perfectly normal in JS:

let myArray = [];
let fibonacci = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34];

However, arrays in JavaScript and in C are two different things. For example, the following, obviously, is not possible in C:

myArray[0] = 5;
myArray[1] = 5.5;
myArray[2] = 'cat';
myArray[3] = [1,2,3];
myArray[4] = (a,b) => {a+b};
myArray[1000] = 'mind blown';
// myArray = [5, 5.5, 'cat', [1,2,3], (a,b) => {a+b}];

In JavaScript, arrays are variable in length. The type of their contents is not controlled - just like the type of ordinary variables. The language takes control of the memory, as a result, the length of the array can increase or decrease, and the developer can not think about it. JavaScript arrays are, in fact, very similar to lists.

Array enumeration can be organized using an unsuccessful method borrowed from C:

let sum = 0;
for (i = 0; i < fibonacci.length; i++) {
  sum += fibonacci[i];
}

However, we do not need to use this approach to enumerating JS arrays. For example, there are unnecessary intermediate variables. In such a design, errors may well arise, the cause of which are undefined or incorrect values. Is there any value in the array element fibonacci[10]? And if the value is there - is it an integer?

But JavaScript has much better mechanisms for working with arrays. Arrays in JS are not just some simple data structures. They, like functions, are first class objects. They have methods to adequately solve various problems:

let sum = fibonacci
   .filter(Number.isInteger)
   .reduce(
      (x,y) => {return x+y}, 0
    );

This is much better than looping through an array for.


Some methods of arrays.

In addition, as already mentioned, the length of arrays in JS, unlike the length of C-arrays, is not fixed. This allows you to have quite interesting effects on arrays that affect their length. So, using the method, you canpopextract the last element from the array. And the methodpushallows you to add a new element to the end of the array. The methodunshiftallows you to add an element to the beginning of the array. And the methodshiftis to extract the first element of the array. Using different combinations of these methods, you can work with arrays as with stacks or queues. It all depends on the needs of the programmer.

Arrays in PHP


Arrays in PHP are almost like JavaScript arrays.

They, like JS arrays, are of variable length and weak typing. Therefore, it may be tempting to decide that arrays in PHP and in JS are the same thing.

$myArray = [];
$fibonacci = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34];
$myArray[0] = 5;
$myArray[1] = 5.5;
$myArray[2] = 'cat';
$myArray[3] = [1,2,3];
$myArray[4] = function($a, $b) { return $a + $b; };

Lambda functions in PHP are not as beautiful as similar functions in JS (in ES6), but this example written in PHP is functionally equivalent to the previously considered JS example.

There can be used, and analogs described above functions to add elements to the array and retrieve them from it ( array_push, array_pop, array_shift, array_unshift).

But in JavaScript (as well as in C) you cannot write something similar to the following (of course, you can write similar code in JavaScript, but it will not work like in PHP):

$myArray['banana'] = 'yellow fruit';
$myArray[5] = 'is alive';
$myArray[0.02] = 'the 2%';

In PHP, from a technical point of view, arrays are hash tables or dictionaries. They use key / value pairs. Keys can be any primitive values: integers, floating point numbers, strings. Since php arrays are based on dictionaries, finding key values ​​in these arrays is extremely efficient. Namely, the time complexity of the search is O(1).

This means that PHP arrays can successfully serve as simple lookup tables:

$colours = [
  'red' => '#FF0000',
  'green' => '#00FF00',
  'blue' => '#0000FF',
  'orange' => '#FF6600',
];

PHP arrays give the developer a lot of flexibility. These arrays can be sorted by key and value. You can, for example, “flip” an array with array_flip, swapping the keys and values, which makes it possible to very efficiently organize a search in the array of the necessary data.

Finding a specific value in a regular array is time-consuming O(n), since during the search you need to check each value stored in the array. And in PHP, it is easy to make the time complexity of the same operation amount to O(1):

$users = [
  1 => 'Andi',
  2 => 'Benny',
  3 => 'Cara',
  4 => 'Danny',
  5 => 'Emily',
];
$lookupTable = array_flip($users);
return $lookupTable['Benny'];

Of course, something similar is also available in JavaScript, although here it will already be necessary to resort to the capabilities of objects. But because of this, you have to make some compromises. Namely, when working with objects, the developer will not have array methods like the ones we talked about above.

If we continue the discussion about PHP arrays, we can say that their enumeration is organized simply and safely. Here it is possible to apply a cycle forresembling the same cycle from C, but before you do this, you should carefully think about why to do just that. PHP, thanks to loops foreach, allows you to solve problems specific to variable length arrays that can contain values ​​of different types:

$sum = 0;
foreach ($myArray as $key => $value) {
  $sum += is_numeric($value) ? $value : 0;
}

The loop gives access to both keys and values, which allows the programmer to work with both.

It is worth noting that PHP arrays differ from JS arrays in that in PHP you have to use functions external to them to perform some operations with arrays:

$sum = 
  array_reduce(
    array_filter($fibonacci, 'is_numeric'),
    function ($x, $y) { return $x + $y; },
    0
  };

It is functional, but not as beautiful as in JavaScript. If you want to write code for working with PHP arrays that resembles the code used in JavaScript (there are strong arguments in favor of this approach), then you may need to look at a specialized solution. Say - to a class Collectionfrom the Laravel framework. However, PHP allows you to create objects whose capabilities resemble those of arrays (for example, they can be processed in loops foreach).

If PHP is your main programming language, you can become accustomed to it and you can completely forget about the power that lurks in its fundamental mechanisms.

PHP arrays are, in a nutshell, the most underestimated and most inconspicuous feature of the language, which, if used correctly, can be of great benefit.

Summary: Question and Answer


Question : What are the similarities and differences between arrays in JavaScript and in PHP?

Answer : in PHP and JavaScript, arrays are essentially weakly typed lists of variable length. In JavaScript, the keys to array elements are ordered integers. In PHP, arrays can be compared both with lists that support sorting and with dictionaries in which it is convenient to search for items by key. The keys of PHP arrays can be any values ​​of primitive types, and you can sort such arrays by keys or by values.

Dear readers! What standard features do you think JavaScript arrays lack most?


All Articles