RE: Re: Avoiding NOTICEs on Array References

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Jochem Maas wrote:
> trlists@xxxxxxxxxx wrote:
>> 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.

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(
  '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

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux