Stuart
Stuart

Reputation: 688

Unset Values from an Array that Match another Array

What would be the quickest and most efficient way of ensuring that the values that match $config['a'] are not set in $config['b']?

In this case Sunday 14 should be unset from $config['b']['Hours']['Sunday']

$duplicates = array_intersect($config['a']['Hours'], $config['b']['Hours']);

Gives me an error, "Notice: Array to string conversion", and incorrect results, so either my array has been constructed incorrectly or my approach is incorrect.

Here is the array;

    $config  =  array(
                "a" => array(
                    "Hours" => array(
                        "Sunday" => array(12,13,14,15,16),
                    ),
                ),
                "b" => array(
                    "Hours" => array(
                        "Sunday" => array(0,1,2,3,4,5,6,7,8,9,10,11,14,17,18,19,20,21,22,23),
                        "Monday" => array(0,1,2,3,4,5,19,18,19,20,21,22,23),
                        "Tuesday" => array(0,1,2,3,4,5,19,18,19,20,21,22,23),
                        "Wednesday" => array(0,1,2,3,4,5,19,18,19,20,21,22,23),
                        "Thursday" => array(0,1,2,3,4,5,19,18,19,20,21,22,23),
                        "Friday" => array(0,1,2,3,4,5,19,18,19,20,21,22,23),
                        "Saturday" => array(0,1,2,3,4,5,8,19,20,21,22,23,24),
                    ),
                ),
            );

Upvotes: 1

Views: 299

Answers (2)

splash58
splash58

Reputation: 26153

To remove from array b values, presented in corresponding 'a', use array_diff function

foreach($config['a']["Hours"] as $k => $v) { 
      $config['b']["Hours"][$k] = array_diff( $config['b']["Hours"][$k], $v);
    }

Upvotes: 0

Jakub Krawczyk
Jakub Krawczyk

Reputation: 970

array_intersect does not work recursively, as specified in the documentation: https://secure.php.net/array_intersect.

It iterates and compares values as strings, thus the error, because it tries to use value array(12,13,14,15,16) as string and fails.

The correct way in your case would be to compare keys first using array_keys(), then for the keys that exist use array_intersect() or array_diff().

Edit:

This example should work in the desired way:

$duplicateKeys = array_intersect(array_keys($config['a']['Hours']), array_keys($config['b']['Hours']));
$duplicates = [];

if(!empty($duplicateKeys) && is_array($duplicateKeys)) {
    foreach($duplicateKeys as $key) {
        $duplicates[$key] = array_intersect($config['a']['Hours'][$key], $config['b']['Hours'][$key]);
    }
}

Upvotes: 2

Related Questions