filter_var() validates or sanitizes a value using a named filter. Validation filters return the filtered value on success and false on failure unless a different failure flag is used.
$email = 'user@example.com';
$result = filter_var($email, FILTER_VALIDATE_EMAIL);
var_dump($result);
$book_id='abc'; // change this to integer to check
if(filter_var($book_id,257)){ // Filter id 257 is for validating integers
echo "Yes true book_id validation passed";
}else{
echo "No false book_id validation failed";
}
output
No false book_id validation failed
We can check a variable by using a particular type of filter by using filter_var() function. This function takes the variable and the ID or name of the filter as input and checks the variable. It returns True of False based on the checking output. bool=filter_var(variable, Filter ID,optional );
You can get list of filter ID here
$email = 'userid@example.com';
if(filter_var($email,FILTER_VALIDATE_EMAIL)){
echo " Yes true, email validation passed";
}else{
echo "No false, email validation failed";
}
output
Yes true, email validation passed
We can replace the email filter name with email filter ID ( 274 ) , just change the above line with this
if(filter_var($email,274)){
$var1 = true; // Change the value to true or false
if(filter_var($var1,FILTER_VALIDATE_BOOLEAN)){
echo " Yes true, Boolean validation passed";
}else{
echo "No false, Boolean validation failed";
}
Output
Yes true, Boolean validation passed
We can set the value based on value.
$var1=true;
$var1 = filter_var('abcd', FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
echo $var1;
echo var_dump($var1); // NULL
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.