Home > Blockchain >  Find missing elements from array based on another (keys not values)
Find missing elements from array based on another (keys not values)

Time:08-24

I need to test an array to make sure it has all elements I am expecing. The twist here is that we are talking about multidimensional arrays. Here is an example:

$required_data = [

    'firstname',
    'lastname',
    'shipping' => [

        'address',
        'city',
        'contacts' => [

            'phone',
            'email'
        ]
    ]
];

$incoming_data = [

    'firstname' => 'Mike',
    'shipping' => [

        'address' => '1st Avenue',
        'contacts' => [

            'phone',
            'email' => '[email protected]'
        ]
    ]
];

I simply need to detect the two missing elements (lastname and city). I don't care about values. I test them separately.

At the moment I'm playing with this function just to get true when all required elements are provided or false otherwise.

It works when $incoming_data doesn't have any value but as soon as I start adding values (eg. Mike, 1st Avenue etc.) it fails.

function validate($incoming_data, $required_data)
{
    foreach ($required as $key => $value) {

        if (!isset($data[$key])) {

            return false;
        }

        if (is_array($data[$key]) && false === validate($data[$key], $value)) {

            return false;
        }
    }

    return true;
}

I can't understand where my function starts playing with values. All is see are comparisons based on keys. Whut?

Thanks.

CodePudding user response:

you have to set empty data in your $required_data tab like so :

$required_data = [
        'firstname' => '',
        'lastname' => '',
        'shipping' => [
            'address' => '',
            'city' => '',
            'contacts' => [
                'phone',
                'email'
            ]
        ]
    ];
  • Related