Jump to content

error array?


Eggzorcist

Recommended Posts

I've been thinking of using an assoc_array for validation code in php to have an associative of all the fields (name, email, message) and to see if there has been an "ERROR" declared in any of them?

 

How would I first declare this array? and How would I check to see if they are empty or any of them contain "ERROR".

 

Thanks

Link to comment
Share on other sites

You can define the array like so:

 


$fields  = array('name','email','message');

// register error like so:

$fields['name']['error'] = 'not enough characters';

// check for error like so:

foreach($fields as $field){

  if(isset($field['error'])){
    // deal with error
    echo $field['error'];
  }

}

 

..note, this is VERY basic and can be done a lot better. Ideally you would have a function to manage your fields and errors and they would likely be two separate arrays but this serves a simple purpose. For example, when you register an error, you could register as an array which would allow you to process multiple errors for a single field.

 

If it's not evident how you can develop the above implementation, I'd advise you read up on building and managing multi-dimensional and associative arrays (lot easier than it sounds).

Link to comment
Share on other sites

Yeh, to use in_array you would likely have to have 2 separate arrays. One for the field names, and another for errors.

 

So, with your previous array of $fields..this is $errors:

 


$errors = array();

$errors['name'] = 'incorrect character count';

if(in_array('name',$errors)){

  //manage error for 'name'

}

 

It would likely be best done using foreach again - but the in_array check would be needless if you managed your field names and errors in the same array.

 

 

Link to comment
Share on other sites

but if I'm looking for each array to send out as a json_encode() and if there is an error it will appear as such $error['message'] = "ERROR" so we can just check $error array, to seek for any "ERROR" in either of ['message'], ['name'], ['email']. Can't I make a really simple if statement using in_array()?

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.