Rae Wuest
Rae Wuest

Reputation: 33

PHP excluding specific variable values from foreach statement

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.

Upvotes: 3

Views: 3178

Answers (1)

Okonomiyaki3000
Okonomiyaki3000

Reputation: 3696

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... 
}

Upvotes: 3

Related Questions