Skip to content
Advertisement

How to check the key of next index of arrays in PHP?

I have an PHP array :

JavaScript

I want to check the keys of each array and if not match need to add it on every array.

Expecting output like:

JavaScript

If the key is not exist need to add the key with value zero. Is that possible?

I tried with array_key_exists() function… But I’m not sure where I want to check, when I’m checking It’s return true(1). I know it’s checking on the same array, Actually I want to know where I will check the condition?

JavaScript

Advertisement

Answer

I came up with this:

JavaScript

I needed used a plethora of array functions. The idea is this: First I gather all the possible ‘keys’ from the array, make them unique, sort them and combine them into a new ‘default’ array containing only zero values. After that I use the array_replace() function to insert this array into the existing $datas array. This function does exactly what you want:

array_replace() replaces the values of array with values having the same keys in each of the following arrays. If a key from the first array exists in the second array, its value will be replaced by the value from the second array.

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