views:

40

answers:

3

Is there a function out there to make sure that any given array conforms to a particular structure? What I mean is that is has particular key names, perhaps particular types for values, and whatever nested structure.

Right now I have a place where I want to make sure that the array getting past has certain keys, a couple holding a certain data type, and one sub-array with particular key names. I've done a lot of run-around because I was passing malformed arrays to it, and finally I'm at the point where I have a bunch of

if ( ! isset($arr['key1']) ) { .... }
if ( ! isset($arr['key2']) ) { .... }
if ( ! isset($arr['key3']) ) { .... }

I would have saved a lot of time and consternation if I could have checked that the array conformed to a particular structure beforehand. Ideally something like

$arrModel = array(
    'key1' => NULL ,
    'key2' => int ,
    'key3' => array(
        'key1' => NULL ,
        'key2' => NULL ,
      ),
);

if ( ! validate_array( $arrModel, $arrCandidate ) ) { ... }

So, the question I'm asking is, does this already exists, or do I write this myself?

A: 

Create an array defining your structure, and then go through a loop of the array you want to check and compare it with the array structure you defined.

Duniyadnd
+2  A: 

Convert array to JSON:

http://us.php.net/manual/en/function.json-encode.php

Then check against a JSON Schema:

http://json-schema.org/

http://jsonschemaphpv.sourceforge.net/

webbiedave
I would have said to XML at first, but JSON is just so much easier to work with... +1
ircmaxell
+1  A: 

It doesn't exist built in.

Maybe try something like (untested):

array_diff(array_merge_recursive($arrCandidate, $arrModel), $arrModel)
PMV
I believe you mean array_merge_recursive
brian_d
I did, thanks. (Updated)
PMV