Skip to content

Instantly share code, notes, and snippets.

@MarceloBonifazio
Last active March 29, 2017 22:01
Show Gist options
  • Save MarceloBonifazio/7ca4e37dd1a2638d7cec69696121e428 to your computer and use it in GitHub Desktop.
Save MarceloBonifazio/7ca4e37dd1a2638d7cec69696121e428 to your computer and use it in GitHub Desktop.
Função para testar informaçoes dentro de um array
<?php
// $_POST["teste"] = "algo";
// $_POST["valor1"] = "algo";
// $_POST["valor2"] = "algo";
$array = array("teste",array("valor2","validar2"),array("valor1","validar1"),array("validar"),array("validar","isso"));
$fields = test_informations($array);
if(!empty($fields)){
echo json_encode($fields);
}
function test_informations(array $array){
$i = 1;
$invalid = array();
foreach($array as $val) {
try{
// If value within the array is an array, means that there is an aggregate function
if(is_array($val)){
if(count($val) < 2){
throw new Exception('Quantity of arguments passed with the '.$i.'º array is invalid');
}
$callback = $val[1];
// If function dosn't exist, throw exception
if(!function_exists($callback)){
throw new Exception('Function '.$callback.' not exist');
}
// Test if post is defined, and if value in post is not empty, finally tests the aggregate function
if(empty($_POST[$val[0]])||!$callback($_POST[$val[0]])) {
$invalid[] = $val[0];
}
}else if(empty($_POST[$val])){
$invalid[] = $val;
}
$i++;
} catch (Exception $e) {
echo $e->getMessage()."<br/>";
}
}
return $invalid;
}
function validar1($field){
return false;
}
function validar2($field){
return true;
}
/* Return
* Can Be logged -> Quantity of arguments passed with the 4º array is invalid
* Can Be logged -> Function isso not exist
* ["teste","valor2","valor1"]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment