How To Compare Two Arrays of Data and Calculate Position Differences

How To Compare Two Arrays of Data and Calculate Position Differences

Sometimes we might want to compare two arrays of data, and determine the positional difference of each value in the array from one to the next. One example of such an application of this might be similar to what you see where a website is keeping track of the position of a programming language for instance. Consider the Tiobe Index which tracks the position of a programming language from month to month. Another example of this type of scenario might be something like http://stats.js.org. Let’s see how we can use PHP to calculate two arrays of data to achieve a similar type of effect.


How to Calculate The Difference With Index Based Arrays

jquery gained 3
VueJS gained 6
d3 did not change
meteor gained 2
FreeCodeCamp gained 3
angular.js lost 4
react lost 2

So first off we have an old array of data. In it, we have various JavaScript libraries to work with. In this first example, we can see it is a simple index based array. The algorithm so to speak is to begin looping through the newest array of data. On each iteration of the loop, we want to capture the current iteration value in a variable. With that, we can use array_search to find this current value as it existed in the old array. Once we have that information, we check to see if it is a new entry or not. If array_search returns false, then we know we have a new entry in the new array. In this case, we just say that the new entry gained whatever the absolute value is from the end of the new array. If array_search returns an integer value, then we now have the position of the current iterating value in the old array. With this, we can now set up the logic to see if the value has gained, lost, or not changed when comparing it’s position in the new array versus the old array. As we can see, when we run the code it calculates positional differences just like we wanted.


How to Calculate The Difference With Associative Arrays

What if the arrays we are dealing with are associative arrays and not simple index arrays? In this case, almost everything is the same. What we will need to do in this case however is to use the array_keys function to convert our associative arrays into index based arrays before we apply the calculations. As we can see below, the code still gives us the results we expect when starting with associative arrays rather than index based arrays.

jquery gained 3
VueJS gained 6
d3 did not change
meteor gained 2
FreeCodeCamp gained 3
angular.js lost 4
react lost 2

How To Compare Two Arrays of Data and Calculate Position Differences Summary

This quick tip type tutorial had a look at how to compare two arrays of data and figure out the differences of each value in the arrays. You may be able to find all kinds of interesting applications of this approach.