1

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),
                    ),
                ),
            );
0

2 Answers 2

2

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]);
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Clever Sod! Works great, Thank you.
0

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);
    }

2 Comments

Might be problematic if $config['b']["Hours"][$k] doesn't exist. Although, if the b array always contains all keys, it is not a problem.
I guess that contains. I hope OP add a check if it'not so

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.