Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I validate the structure of my PHP arrays?

Tags:

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?

like image 368
user151841 Avatar asked Oct 27 '10 19:10

user151841


People also ask

Is array validation laravel?

Luckily, Laravel provides a simple way to validate arrays and nested array input with the use of dot notation and the * character. The * character replaces the iteration number of the element in the array. It's also pretty useful when we have more complex nesting going on.

How do I check if an object is an array in PHP?

The is_array() function checks whether a variable is an array or not. This function returns true (1) if the variable is an array, otherwise it returns false/nothing.

How do you validate an array in JavaScript?

In JavaScript, we can check if a variable is an array by using 3 methods, using the isArray method, using the instanceof operator and using checking the constructor type if it matches an Array object. The Array. isArray() method checks whether the passed variable is an Array object.


2 Answers

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/

like image 151
webbiedave Avatar answered Sep 19 '22 09:09

webbiedave


It doesn't exist built in.

Maybe try something like (untested):

array_diff(array_merge_recursive($arrCandidate, $arrModel), $arrModel)
like image 43
Parris Varney Avatar answered Sep 22 '22 09:09

Parris Varney