Recursive key value checks in PHP

 I recently came across a situation where I needed to check if a particular deep nested multidimensional array contained specific keys. The idea was to check a data array against a key array to ensure that no bad data had been supplied.

Recursion to the rescue. This took a while to figure out but is actually quite simple really.

Here is a sample array and a sample check template:


$template= ['id', 'name', 'description', 'active'];

 $values = ['id' => 1, 'name'=>'My product'];

The recursive method itself is below:


    private static function recurse($data, $template)

    {

        foreach ($data as $key => $value)  {

            if(is_array($value)) {
                self::recurse($value, $template[$key]);

            }

            if(!in_array($key, $template) && !is_array($template[$key])) {
                throw new \Exception($key.' missing');

            }

        }

        return true;
    }

What the recursive method does is checks if the template item is an array, otherwise it checks the value against the data's key. Any issues with the incoming data are then thrown out. If all is successful, the next part of the code can be run.


Why would you need this?

You are using an API and all you need to do is ensure the data is supplied is allowed. The API will do all the type checking for you usually and therefore you do not have to be as responsible for the data check.

Comments