Current Location: Home> Latest Articles> How to Use get_defined_constants() and array_filter() to Filter Specific Constants?

How to Use get_defined_constants() and array_filter() to Filter Specific Constants?

M66 2025-06-27

In PHP development, it's common to define many constants to maintain code readability and manageability—such as system-level configurations, error codes, or permission identifiers. As the project scales up, the number of constants inevitably grows. Occasionally, we need to filter out a specific group of constants for particular use cases. This is where get_defined_constants() and array_filter() come in handy.

get_defined_constants() Overview

get_defined_constants() is a built-in function used to retrieve all the constants currently defined in the script. It returns a multidimensional associative array, grouped by category (e.g., Core, user, date, etc.) by default.

Example usage:

print_r(get_defined_constants());  

Partial output:

Array  
(  
    [Core] => Array  
        (  
            [E_ERROR] => 1  
            [E_WARNING] => 2  
        )  
    [user] => Array  
        (  
            [MY_APP_ENV] => 'production'  
        )  
)  

If you pass the parameter true, the constants will be grouped by category. If set to false or omitted, it returns a flat associative array.

array_filter() Overview

array_filter() is another powerful tool that applies a callback function to each element of an array, filtering out elements that don’t meet the criteria. Elements for which the callback returns true are retained.

Basic usage:

$filtered = array_filter($array, function($value) {  
    return $value > 10;  
});  

Practical Example: Filtering Custom Constants

Suppose you've defined some constants prefixed with APP_ to represent application settings:

define('APP_NAME', 'MyApp');  
define('APP_ENV', 'production');  
define('APP_DEBUG', true);  
define('VERSION', '1.0.0');  

Now you want to filter out all constants that start with APP_. Here's how you can use get_defined_constants() in combination with array_filter():

$allConstants = get_defined_constants(true);  
$userConstants = $allConstants['user'] ?? [];  
<p>$appConstants = array_filter($userConstants, function($key) {<br>
return strpos($key, 'APP_') === 0;<br>
}, ARRAY_FILTER_USE_KEY);</p>
<p>print_r($appConstants);<br>

Output:

Array  
(  
    [APP_NAME] => MyApp  
    [APP_ENV] => production  
    [APP_DEBUG] => 1  
)  

This allows you to precisely extract all custom constants that start with APP_, which is useful for tasks like exporting configurations or debugging.

Advanced Example: Convert Result to JSON and Send to API

You can also convert the filtered constants into JSON and send them to a remote API (e.g., a logging system or config center). For example, sending the data to https://m66.net/api/report_constants:

$payload = json_encode($appConstants);  
<p>$ch = curl_init('<a rel="noopener" target="_new" class="" href="https://m66.net/api/report_constants">https://m66.net/api/report_constants</a>');<br>
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);<br>
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);<br>
curl_setopt($ch, CURLOPT_HTTPHEADER, [<br>
'Content-Type: application/json',<br>
'Content-Length: ' . strlen($payload)<br>
]);</p>
<p>$response = curl_exec($ch);<br>
curl_close($ch);</p>
<p>echo "Server response: " . $response;<br>

Summary

By combining get_defined_constants() and array_filter(), you can flexibly filter specific categories of constants from the entire list. Whether for debugging, configuration export, or remote transfer, this combo is a highly practical technique that every PHP developer should master.