Get a list of all available constants with PHP

Posted in PHP -

PHP has the function get_defined_constants() which allows you to get a list of all the available constants in an array. This post looks at how to use the get_defined_constants() function and example output from it.

The get_defined_constants() function takes one optional parameter, which specifies whether or not to categorise the constants. The default is false, which means an associative array is returned containing the constant name as the key and the constant value as the value. If the categorise parameter is set to true, a multi-dimensional array is returned containing the section names as the index and then a sub array of name-value pairs in the second dimension.

For example:

print_r(get_defined_constants());

will output something like this:

Array
(
    [E_ERROR] => 1
    [E_WARNING] => 2
    [E_PARSE] => 4
    [E_NOTICE] => 8
    [E_STRICT] => 2048
    [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
    [FALSE] => 
    [NULL] => 
    [ZEND_THREAD_SAFE] => 
    [PHP_VERSION] => 5.1.6
    [PHP_OS] => Linux
    [PHP_SAPI] => apache2handler
    [DEFAULT_INCLUDE_PATH] => .:/usr/share/pear
...

and

print_r(get_defined_constants(true));

will output something like this:

Array
(
    [internal] => Array
        (
            [E_ERROR] => 1
            [E_WARNING] => 2
            ...
        )
    [libxml] => Array
        (
            [LIBXML_VERSION] => 20626
            [LIBXML_DOTTED_VERSION] => 2.6.26
            ...
        )
    [xml] => Array
        (
            [XML_ERROR_NONE] => 0
            [XML_ERROR_NO_MEMORY] => 1
            ...
         )
    ...
)

If you have any user defined constants they will be listed at the end when not categorised, and in a [user] section when categorised.



Related posts:


Comments