views:

65

answers:

2

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 it?

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;

}
+4  A: 
$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?

VolkerK
Note that it's safer to avoid `$_REQUEST` and explicitly use `$_GET` or `$_POST`. Helps against CSRF.
Reinis I.
A: 

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...

PhiLho