Skip to content
Advertisement

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

I have an PHP array :

$datas = array(
    "abcd" => array(
        "1639340364" => 1,
        "1639362752" => 85,
        "1639363500" => 74,
    ),
          
    "efgh" => array(
        "1639340364" => 78,
        "1639362754" => 98,
        "1639363500" => 46,
    ),
      
    
    "ijkl" => array(
        "1639340364" => 78,
        "1639362754" => 98,
        "1639363505" => 46,
    ),
);

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

Expecting output like:

$datas = array(
      
    "abcd" => array(
        "1639340364" => 1,
        "1639362752" => 85,
        "1639362754" => 0,
        "1639363500" => 74,
        "1639363505" => 0,
    ),
          
    
    "efgh" => array(
          
        
        "1639340364" => 78,
        "1639362752" => 0,
        "1639362754" => 98,
        "1639363500" => 46,
        "1639363505" => 0,
    ),
      
    
    "ijkl" => array(
        "1639340364" => 78,
        "1639362752" => 0,
        "1639362754" => 98,
        "1639363500" => 0,
        "1639363505" => 46,
    ),
);

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?

foreach($datas as $key => $data ){
  print_r($data);
  foreach($data as $key => $point ){
    $val = array_key_exists($key,$data);
    echo $val;
  }
}

Advertisement

Answer

I came up with this:

// prepare default keys
$keys = [];
foreach ($datas as $data) {
    $keys = array_merge($keys, array_keys($data));
}
$keys = array_unique($keys);
sort($keys);

// construct default array with zeros
$default = array_combine($keys, array_fill(0, count($keys), 0));

// insert the default array
foreach ($datas as $key => $data) {
    $datas[$key] = array_replace($default, $data);
}

// show result
echo '<pre>';
print_r($datas);
echo '</pre>';

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