How to check an array quickly?

Asked

Viewed 39 times

1

Hello, on my system I get a request in JSON format and soon after it is decoded.

This is the mandatory model that the requisition must have.

array (
 "client_id" => "",
 "credentials" => array("email" => "", "password" => ""),
 "security_questions" => array("1" => "", "2" => "", "3" => "");
  "security_answers" => array("1" => "", "2" => "", "3" => "");
)

How can I check if the request received by my system follows the required model and also check if there is an empty value without using multiple IF/IF ELSE? The goal would be to make the code smaller.

1 answer

1


There are some libraries that already implement what you want. For example, particle/validator.

To install through Composer:

$ composer require particle/validator

Thus, you can define your validator:

use Particle\Validator\Validator;

$validate = new Validator;

$validate->required('client_id')->integer()->greaterThan(0);
$validate->required('credentials.email')->email();
$validate->required('credentials.password')->lengthBetween(4, 10);
...

$result = $validate->validate($data);

if (!$result->isValid()) {
    print_r($result->getMessages());
    exit;
}

...

More information you can see on official documentation.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.