开发者

Is there a concise way to test GET parameter combinations in PHP?

The code below checks for GET params. There are two selects on the page which filter a list by type and age group.

I'm looking for a way to refactor the conditional which test the type/age combinations. Is there a more clear/concise way to write 开发者_如何学Pythonit?

if ( isset($_REQUEST['type']) || isset($_REQUEST['age']) )
{
  // we need to do something

  $type = ( $_REQUEST['type'] == 'all' ? false : (int)($_REQUEST['type']) );
  $age = ( $_REQUEST['age'] == 'all' ? false : (int)($_REQUEST['age']) );


  // test the possible type/age combinations

  if ($type && $age) 
  {            
    $cats = $type . "," . $age;
  }
  elseif ($type)
  {
    $cats = $type;
  }
  elseif ($age)
  {
    $cats = $age;
  }
  else
  {
    $cats = false;
  }

  // do stuff with $cats;

}


$cat = array(
  $_REQUEST['type'] == 'all' ? false : intval($_REQUEST['type']),
  $_REQUEST['age'] == 'all' ? false : intval($_REQUEST['age'])
);

$cat = join(',', array_filter($cat));
echo $cat;

If both ['type'] and ['age'] are 'all' the result will be "", i.e. string(0). So it's not identical. Whether this is a problem or not depends on how you use $cat. E.g. if (!$cat)will still work since an empty string is converted to false in a boolean context.

edit: oops, and there's another difference. I use array_filter() without a (specific) callback.

If no callback is supplied, all entries of input equal to FALSE (see converting to boolean) will be removed.

E.g. $_REQUEST = array('type'=>'0', 'age'=>'0') will also result in $cat="".
Is this a problem in your context?


Not sure if it is clearer, but at least it is a bit more concise... :-)

$cats = str_replace('all', '', "${_GET['type']},${_GET['age']}");
$cats = preg_replace('/^,|,$/', '', $cats);

[EDIT] Give a simpler version...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜