Skip to content

Instantly share code, notes, and snippets.

@datamafia
Created June 3, 2014 22:05
Show Gist options
  • Save datamafia/17e84d4412d87dbb8ba4 to your computer and use it in GitHub Desktop.
Save datamafia/17e84d4412d87dbb8ba4 to your computer and use it in GitHub Desktop.
Blog post support for simple validation using PHP's array_intersect_keys
<?php
/* Check for presence of multiple keys in PHP using array_intersect_key
* @param $a : array of data to be checked
* @param $required : array of keys required
* @datamafia // -- Marc
*/
// array to validate
$a = array(
'key1' => 'value1',
'key2' => 'value2',
'key3' => 'value3',
);
// required keys for validation
$required = array('key1'=>null, 'key2'=>null);
// returns an array of intersections (matches)
$res = array_intersect_key($required, $a);
// validate the intersection with the required keys
if(count($res) != count($required)){
echo 'FAIL';
}else{
echo 'PASS';
}
echo "\r\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment