0

Thank you for help. Anyway, i'm a student and i'm stuck making a function that does a simple empty() check on a key in a array. If it is empty() -> it will fill in the error and print it on a div element.

This is my code:

 function validateData($data, $formErrors) {

    if (empty($data)) {
        $formErrors = 'name is required.';
      }
    echo $formErrors;
}

Executing the function:

  $data = $_POST;
  $formErrors = [];

  // Elementen valideren
  validateData($data['name'], $formErrors['name'] = '');

This is the thing that i want to achieve:

if (empty($data['surname'])) {
    $formErrors['surname'] = 'Surname is required.';
  }

Looks like it is not returning the value of that key or whatelse?

Thanks alot!

1 Answer 1

1

You need to make it a reference parameter with & if you want to assign it in the function.

function validateData($data, &$formErrors) {

    if (empty($data)) {
        $formErrors = 'name is required.';
      }
    echo $formErrors;
}

And you can't use an expression when passing a reference parameter, it has to be just the variable. It should be:

$formErrors = ['name' => ''];
validateData($data['name'], $formErrors['name']);
Sign up to request clarification or add additional context in comments.

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.