How to echo filter used in filter_var

279 Views Asked by At

First I'll show the function:

function validate($data, $filter){
  if(!filter_var($data, $filter))
  { 
     return 'Filter used:'.$filter;
  }
  else
  {
     return 'good';
  }
}

When I use this function it will look like this:

$email = '[email protected]';
echo validate($email, FILTER_VALIDATE_EMAIL);

Output is:

Filter used: 274

The problem is that I want the output to be:

Filter used: FILTER_VALIDATE_EMAIL.

2

There are 2 best solutions below

1
On

FILTER_VALIDATE_EMAIL is a named constant that is set to 274. Your validate() function never sees "FILTER_VALIDATE_EMAIL", it just sees 274 being passed into it and passes 274 to filter_var(), which knows how to handle it.

One advantage of constants for the developer is: by using an IDE with auto-complete and code intelligence, you can be certain of the variable's name and thus can avoid possible typos.

Look at @AbraCadaver's answer for an elegant solution to your query.

0
On

To get the actual constant name you probably need to pass the filter as a string and use constant():

function validate($data, $filter){
  if(!filter_var($data, constant($filter)))
  { 
     return 'Filter used:'.$filter;
  }
  else
  {
     return 'good';
  }
}

Then use it like:

echo validate($email, 'FILTER_VALIDATE_EMAIL');

I got to thinking about multiple flags, and I was bored. This could get really messy but for simple filters it works:

function validate(){    
  $args = func_get_args();
  $data = array_shift($args);
  $con_args = array_map('constant', $args);
  array_unshift($con_args, $data);

  if(!call_user_func_array('filter_var', $con_args))
  { 
     return 'Filter used:'.implode(', ', $args);
  }
  else
  {
     return 'good';
  }
}

echo validate($url, 'FILTER_VALIDATE_URL', 'FILTER_FLAG_PATH_REQUIRED');