Skip to content

Instantly share code, notes, and snippets.

@richardpq
Created September 17, 2015 01:10
Show Gist options
  • Save richardpq/9f14a20e73eae9ecc4c8 to your computer and use it in GitHub Desktop.
Save richardpq/9f14a20e73eae9ecc4c8 to your computer and use it in GitHub Desktop.
Usually when you want to validate if the parameters you are receiving from a client has valid keys, you use a foreach to compare each parameter key with an array of valid keys, but this way is shorter and faster.
<?php
$invalidParameters = ['Key_1' => 1, 'Key_2' => 2, 'No_valid' => 3];
$validParameters = ['Key_1' => 1, 'Key_2' => 2];
function validParameters($parameters) {
$validKeys = ['Key_1', 'Key_2', 'Key_3', 'Key_4'];
$keys = array_keys($parameters);
return array_diff($keys, $validKeys) ? false : true;
}
var_dump(validParameters($invalidParameters), validParameters($validParameters)); // bool(false), bool(true)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment