0

I made the function which will return me an array with all unprovided informations from user, but I can't get it to work with first element in array.

This is the data which is used as parameter in function:

$data = array(
  $_POST["firstName"] => "first name",
  $_POST["lastName"] => "last name"
);

print_r(return_not_provided($data));

This is the function:

function return_not_provided($formFields) {

    $notProvidedFields = array();

    foreach ($formFields as $field => $value) {
        if (!isset($field) || empty($field))
            array_push($notProvidedFields, $value);
    }

    return $notProvidedFields;

}

And it returns this:

Array ( [0] => last name )

Script notifies me that both indexes are undefined (firstName and lastName) but doesn't push them both in array.

Nikola Stojaković
  • 2,257
  • 4
  • 27
  • 49
  • 1
    Your main issue is that you try to use two undefined indexes. So when you try to use them they get converted to an empty string `""` and you also get a notice for them. Since you try to use two of them as key the second one, which also gets silently converted to `""`, overwrites the first one, since you can't have two identical keys in an array. So that you just see one element in the array is just a follow up result, since the array you pass to the function already just has one element. The main solution is to check first if the index exist, before you use them as keys. – Rizier123 Feb 06 '17 at 20:40
  • It seems like you're creating the array backwards. It should presumably be `array('first name' => $_POST['firstName'], 'last name' => $_POST['lastName'])` – Barmar Feb 06 '17 at 20:41

0 Answers0