Google News
logo
PHP program to create a case in-sensitive constant using define() function
To create a case-insensitive constant in PHP using the `define()` function, we can use the `strcasecmp()` function to compare the constant name with the input string in a case-insensitive manner. Here is an example :
Program :
<?php
define_case_insensitive('MY_CONSTANT', 'Hello, world!');

function define_case_insensitive($name, $value) {
    $constants = get_defined_constants(true)['user'];
    foreach ($constants as $constantName => $constantValue) {
        if (strcasecmp($constantName, $name) === 0) {
            return false; // constant already defined with this name
        }
    }
    define($name, $value);
    return true;
}

echo MY_CONSTANT; // outputs "Hello, world!"
echo my_constant; // outputs "Hello, world!"
echo My_Constant; // outputs "Hello, world!"
?>
In this example, the `define_case_insensitive()` function is defined to create a case-insensitive constant. It takes two arguments: the name of the constant and its value.

First, it retrieves all user-defined constants using the `get_defined_constants()` function and loops through them to check if a constant with the same name already exists, ignoring case.

If it does, the function returns false and the constant is not defined. If not, the `define()` function is used to define the constant with the given name and value, and the function returns true. Finally, the constant can be accessed using any case variation of its name.