How to get all the pre-defined constants list in PHP?

pre defined-php-constants-list

It happens for all developers to desperately find the list of defined constant of projects while working on a medium or a large scale of projects. Using constants is a very important part to save more time for other things and trying to access some specific values all over the project’s page. Well, PHP provides a unique function that will return the list of all the defined constants.

get_defined_constants();

It returns an associative array with the names of all the constants and their values.

get_defined_constants(bool $categorize = false): array

For more details, you can visit here.

The output of  this function with boolean false will look like something similar to:

Array
(
    [E_ERROR] => 1
    [E_WARNING] => 2
    [E_PARSE] => 4
    [E_NOTICE] => 8
    [E_CORE_ERROR] => 16
    [E_CORE_WARNING] => 32
    [E_COMPILE_ERROR] => 64
    [E_COMPILE_WARNING] => 128
    [E_USER_ERROR] => 256
    [E_USER_WARNING] => 512
    [E_USER_NOTICE] => 1024
    [E_ALL] => 2047
    [TRUE] => 1
)

By the mean of $category boolean in this function:
categorize

Causing this function to return a multi-dimensional array with categories in the keys of the first dimension and constants and their values in the second dimension.

<?php
define("MY_CONSTANT", 1);
print_r(get_defined_constants(true));
?>

The above example will output something similar to:

Array
(
    [Core] => Array
        (
            [E_ERROR] => 1
            [E_WARNING] => 2
            [E_PARSE] => 4
            [E_NOTICE] => 8
            [E_CORE_ERROR] => 16
            [E_CORE_WARNING] => 32
            [E_COMPILE_ERROR] => 64
            [E_COMPILE_WARNING] => 128
            [E_USER_ERROR] => 256
            [E_USER_WARNING] => 512
            [E_USER_NOTICE] => 1024
            [E_ALL] => 2047
            [TRUE] => 1
        )
    [user] => Array
        (
            [MY_CONSTANT] => 1
        )
)

To get more knowledge about PHP topics in detail, please check this link here.

Please follow and like us:

Related Posts

Leave a Reply

Share