3

I am trying to exclude fields from a form from being required. Currently the entire array payment runs through this for each statement. I am trying to keep the fields extra, extra2 and extra3 from being required. The can be set to null or defined as whatever string if empty. This is what I have currently:

  foreach($p as $key => $value) {
    $value = trim($value);
    if($value == '') {
      $keyName = preg_replace('/([A-Z])/', " $1", $key);
      $this->_errors['Payment ' . $keyName] = __('Payment ','cart66') . $keyName . __(' required','cart66');
      $this->_jqErrors[] = "payment-$key";
    }

This is what I have tried, but to no avail:

 foreach($p as $key => $value) {
    $value = trim($value);
    if($value == '' && $p != 'extra' || 'extra2' || 'extra3') {
      $keyName = preg_replace('/([A-Z])/', " $1", $key);
      $this->_errors['Payment ' . $keyName] = __('Payment ','cart66') . $keyName . __(' required','cart66');
      $this->_jqErrors[] = "payment-$key";
    }
else if ($p['extra'] == '') {
 $_p['extra'] = NULL; 
}
else if ($p['extra2'] == '') {
 $_p['extra2'] = NULL; 
}
else if ($p['extra3'] == '') {
 $_p['extra3'] = NULL; 
}

}

It's my syntax isn't it? The database itself is set to accept null and is not primary or unique.

1 Answer 1

3

One good way would just be to check at the top of the loop and continue if you're in on a field that should be excluded.

$exclude = array('field1', 'field2', ...);
foreach ($p as $key => $value)
{
    if (in_array($key, $exclude)) { continue; }

    // your code... 
}
Sign up to request clarification or add additional context in comments.

4 Comments

That went the opposite way, it excluded everything but the fields I want to exclude, but I can absolutely handle it from here. Thank you very much. Is this a different approach to the array_diff Benjamin was offering?
Yes, he is suggesting that you actually strip out the unneeded elements from your array before looping and then (if necessary) reinsert them afterward. Probably some performance benefit to doing it that way if you have quite large arrays but for typical input arrays the difference should be negligible so use whichever gives you the most readable, maintainable code.
should I put the "!" in my if condition to so what I really want right?
@LuísAlmeida I don't know. It depends on what you want.

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.