Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
FILTER_CALLBACK constant in PHP
The FILTER_CALLBACK constant calls a user−defined function to filter the value. This constant is used with filter_var() to apply custom filtering logic by passing a callback function.
Syntax
filter_var($value, FILTER_CALLBACK, array("options" => "callback_function"));
Parameters
The callback function is specified in the options array and receives the input value as a parameter. The function should return the filtered value.
Example 1: Using Built−in Function
This example converts a string to lowercase using PHP's built−in strtolower() function ?
<?php
$string = "DEMO TEXT!";
echo filter_var($string, FILTER_CALLBACK, array("options" => "strtolower"));
?>
demo text!
Example 2: Using Custom Function
This example demonstrates using a custom callback function to remove spaces and convert to uppercase ?
<?php
function customFilter($value) {
return strtoupper(str_replace(' ', '_', $value));
}
$string = "hello world php";
echo filter_var($string, FILTER_CALLBACK, array("options" => "customFilter"));
?>
HELLO_WORLD_PHP
Example 3: Using Anonymous Function
You can also use anonymous functions as callbacks ?
<?php
$number = "123.456";
$rounded = filter_var($number, FILTER_CALLBACK, array(
"options" => function($value) {
return round((float)$value, 1);
}
));
echo $rounded;
?>
123.5
Conclusion
FILTER_CALLBACK provides flexible data filtering by allowing custom functions. It's useful when built−in filters don't meet specific requirements, enabling you to apply any transformation logic to input data.
