Skip to content
Advertisement

How do I compared 2 nested index lengths?

First time posting here, I try to follow the questioning guides, sorry if I missed something.

I got a multidimensional array in PHP that do not have the same amount of results. Array[0] contains 6 while Array[1] only contains 4. here’s an example:

JavaScript

I managed to sum these 2 multidimentional arrays, using the following code:

JavaScript

So my result is:

JavaScript

So the SUM worked fine for the first 4 values, but then the last two are not matching the pattern.

What I am trying to achieve: In my database, I got an average number of each array. So basically what I would like the array_sum to do is:

JavaScript

To summarise: I am trying to achieve that the array with less values gets filled up with the average_variable_number which I pull from my MySQL database.

I tried a few things, but I can’t wrap my head around it. I’ve been searching for a few days without any luck or tips where I have to look into.

Hope someone can show me an example of what the foreach function should look like to achieve the above.

Thank you a million in advance!!!

Advertisement

Answer

If it’s always just 2 arrays, you can loop up to the longer length, then test whether the element exists in both arrays, replacing a nonexistent element with the default value.

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement