3

I have this method called validate() that accepts array as parameter.

E.g.

$v->validate([
    'username' => [$username, 'required'],
    'email'    => [$email, 'required'],
    'password' => [$password, 'required'],
]);

So what I want to do is, create dynamically parameters for that. Don't know the right term though. For example!

$v->validate([
    'username' => [$username, 'required'],
    'email'    => [$email, 'required'],
    'password' => [$password, 'required'],            
    $validate_parameters
]);

Something like that, there's this fixed fields and other dynamic fields that will be sent as a parameter. It will be translated as:

$v->validate([
    'username'       => [$username, 'required'],
    'email'          => [$email, 'required'],
    'password'       => [$password, 'required'],
    'dynamicfield_1' => ['value_1', 'rule_1'],
    'dynamicfield_2' => ['value_2', 'rule_2'],
    'dynamicfield_3' => ['value_3', 'rule_3'],
]);

Here's my method for that.

public function validateDynamicFields($compressed_field, $rules) {

    $parameters = '';

    foreach ($compressed_field as $key => $value) {

        // Well technically this will not work since it's not even an array or some sort.
        $parameters .= $key => [$value, $rules];

        // I even tried this and hope that it would work but it doesn't
        // $parameters .= "'{$key}' => [{$value}, '{$rules}'],";

    }

    return $parameters;
}

The question is, how do I create dynamically array values for the validate() method?

1
  • 2
    Have you tried array_merge? You can generate the "dynamic fields" inside the method and merge it with the user supplied fields. Commented Sep 16, 2015 at 7:04

2 Answers 2

2

You can use array_merge:

$v->validate(array_merge(
    [
      'username' => [$username, 'required'],
      'email'    => [$email, 'required'],
      'password' => [$password, 'required']
    ],
    $validate_parameters
));
Sign up to request clarification or add additional context in comments.

Comments

2

Im not sure what you are trying to accomplish, but maybe something like this: It creates both arrays separately, then merges them

$staticFields = [
    'username' => [$username, 'required'],
    'email'    => [$email, 'required'],
    'password' => [$password, 'required']
];

//this can be assigned with your DynamicFields function
$dynamicFields =  [
    'dynamicfield_1' => ['value_1', 'rule_1'],
    'dynamicfield_2' => ['value_2', 'rule_2'],
    'dynamicfield_3' => ['value_3', 'rule_3']
];

//merge both arrays, and pass them
$v->validate(array_merge($staticFields, $dynamicFields));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.