Skip to content
Advertisement

PHP using an array in a Validation Class

On my site I have my register page, where a user inputs his information to register to my site.

When he does the I process the user inputted information. Now when processing it I’m using arrays to facilitate the process, and not have me write the same code over and over. For example, here is how I gather the user information and check it using a method in my validation class.

$data = array(
   $_POST['firstname'] => "First Name",
   $_POST['lastname'] => "Last Name"
);

foreach($data as $userInput => $fieldName) {
   $validation = new Validation();
   $result = $validation->checkEmpty($userInput, $fieldName);
}

Now this all works for me on my page, I’m able to check to see if the user left something empty on the register with the method “checkEmpty”, which also returns an array of the fields left empty. I didn’t show the method because it’s not part of my problem. Now, here’s my question, I want to also check the length of the fields. What would be a good way for me to do this without rewriting things over and over? Would I have to do another array?

I’m thinking something like this, maybe?

$data2 = array(
  $_POST['firstname'] => 30,
  $_POST['lastname'] => 35
),

foreach($data as $userInput => $limit) {
   $result = $validation->checkLength($userInput, $limit);
}

But where I get stumped is, if one the inputted fields is too long, how do return which one it was if in the array I passed through I don’t have the field name to which it belongs? I thought of a multi-dimensional array, but I’m not sure if that will work.

Advertisement

Answer

I would think using the field names as keys for your array may be a better approach. Then yeah, use a multi-dimensional array something like this.

$data = array(
   'First Name' => array($_POST['firstname'], 30),
   'Last Name' => array($_POST['lastname'], 35)
)
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement