Re: Re: if elseif elseif elseif....

From: Date: Thu, 05 Mar 2009 23:16:47 +0000
Subject: Re: Re: if elseif elseif elseif....
References: 1 2  Groups: php.general 
Request: Send a blank email to php-general+get-289416@lists.php.net to get a copy of this message
Rather than encoding all the variable names into one long unwieldy set of statements, I would put them all into an array, and then use a loop to process the array. This way all the variable names are together, and the next time you want to enter another set of variables you can use the same code, but read from a different array. For example: $oblig_fields = array('TitleN', 'first_nameN', '....'); $ok = true; $i = 0; while ($i < count($oblig_fields && $ok)) { if (!isset($_POST[$oblig_fields[$i]]) || ($_POST[$oblig_fields[$i]] == '')) { $ok = false; } else { $results[$oblig_fields[$i]] = $_POST[$oblig_fields[$i]]; } ++$i; } if (!$ok) { echo 'Scream!!!'; }
The problem with that is if I miss 5 fields, I have 5 page refreshes to get to the end & actually successfully submit the form. If you keep an array of broken entries (per my previous suggestion) you get all the form fields missed in one go. I'd just do a foreach instead of a while, count, and counter. foreach ($oblig_fields as $field_name) { if (!isset($_POST[$field_name]) || empty($_POST[$field_name])) {
    ....
} }
I am sure you could use a "break" statement in place of the "$ok = false;" above, but I have never trusted the break statement. To my mind it is like a GOTO without a target.
Must've been a bad experience ;) Always works for me. It breaks out of the current loop (for, foreach, while - doesn't matter about the loop syntax) or switch and continues executing the code straight after the loop. -- Postgresql & php tutorials http://www.designmagick.com/

« previous php.general (#289416) next »