Re: Re: Avoiding NOTICEs on Array References
| From: | Jochem Maas | Date: | Thu, 27 Jan 2005 09:17:02 +0000 |
| Subject: | Re: Re: Avoiding NOTICEs on Array References | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-207455@lists.php.net to get a copy of this message | ||
Michael Sims wrote:
Jochem Maas wrote:Its a good idea - although to make this example work I believe you would need to use array_merge_recursive() - which does what you mean ;-)trlists@clayst.com wrote:Here's an approach that I like which I think cuts down on the clumsy constructs. On a "controller" page (the C in MVC) that handles form submissions I create an array which defines what form variables are available and their default values if not entered. I then use array_merge() to combine that array with $_POST (or $_GET, as the case may be) and the result is an array that contains all of my form variables with each guaranteed to be set and contain a sane default. array_merge() works in such a way that values in the first default array will only be replaced if they actually exist in $_POST, which is what I want. (Contrived) example: $formVars = array_merge(array(If one must check the value and not just the existence of the checkbox entry, or for other uses, e.g. where a flag may or may not be present, one is saddled with clumsy constructs like: if (($isset($array['index']) && ($array['index'] == 1)) ...okay, I get where your coming from - indeed nasty business them checkboxes.'firstName' => '', 'lastName' => '','contactMethod' => 'email','flags' => array('one' => 0, 'two' => 0, 'three' => 0)), $_POST);
The above handles the case where you have: <input type="checkbox" name="flags[one]" value="1"> <input type="checkbox" name="flags[two]" value="1"> <input type="checkbox" name="flags[three]" value="1"> Now, I do: if (!empty($_POST)) { if (trim($formVars['firstName']) == '') {//complain that first name is required} if ($formVars['flags']['one']) {//handle the case where the first checkbox is checked} ... } This way I can safely reference anything in $formVars under E_ALL without throwing notices. I think it's a lot cleaner than the constant (!isset($_POST['var']) || $_POST['var'] == '') stuff...YMMV