392 of 410 menu

The get_defined_constants Function

The get_defined_constants function returns an array with all currently defined constants. The function can take an optional parameter, which allows getting constants only of a specific category. The returned array contains constant names as keys and their values.

Syntax

get_defined_constants(bool $categorize = false);

Example

Get all defined constants:

<?php define('MY_CONST', 'test'); $res = get_defined_constants(); print_r(array_slice($res, 0, 3)); ?>

Code execution result (first 3 elements):

[ 'E_ERROR' => 1, 'E_WARNING' => 2, 'MY_CONST' => 'test' ]

Example

Get constants grouped by categories:

<?php $res = get_defined_constants(true); print_r(array_keys($res)); ?>

Code execution result (example):

[ 'Core', 'pcre', 'user' ]

Example

Check for the presence of a specific constant:

<?php $constants = get_defined_constants(); if (isset($constants['PHP_VERSION'])) { echo 'PHP version: ' . $constants['PHP_VERSION']; } ?>

Code execution result (example):

'PHP version: 8.1.0'
byenru