PHP arrays: indexed vs keyed
I have a method, fetch_widgets
, that fetches widgets from the (MySQL) database. I pass it an $options
array so I can selectively add WHERE
and JOIN
clauses, add/remove columns etc.
For example:
$options = array();
$options[] = 'include_disabled';
$options[] = 'include_tag_ids';
$options['start_date'] = '2011-01-01';
$options['end_date'] = '2011-01-31';
In fetch_widgets
I check for the options using either:
if(array_key_exists('st开发者_JS百科art_date',$options)) { ... }
or:
if(in_array('include_tag_ids',$options)) { ... }
depending on whether or not the option is activated just be being present (e.g. include_disabled
) or has a key and a value (e.g. end_date
).
I'm running into difficulties because I'm getting strange results from in_array
when the $options
array contains keyed and non-keyed values. Can anyone shed any light on this?
Don't mix/match keyed and non-keyed arrays if you need consistent behavior.
Instead, do something like this:
$options = array();
$options['include_disabled'] = true;
$options['include_tag_ids'] = true;
$options['start_date'] = '2011-01-01';
$options['end_date'] = '2011-01-31';
精彩评论