Current Location: Home> Latest Articles> How to define array constants using PHP define?

How to define array constants using PHP define?

gitbox 2025-05-28

In PHP, the define function is mainly used to define constants. In PHP 5.6 and previous versions, define can only define constants of scalar type, such as strings, integers, and boolean values. After PHP 7, the define function supports directly defining array constants, which allows us to more conveniently use arrays as unchangeable configurations or data.

1. What are array constants?

Array constants refer to arrays defined in constants and cannot be modified after definition. This means that the array constants you define remain unchanged when the code is running, which is very suitable for storing configuration information, fixed parameters, etc.

2. How to define array constants with define ?

PHP 7+ version supports directly defining array constants with define . The specific syntax is as follows:

 define('Constant name', Array);

To give a simple example:

 define('FRUITS', ['apple', 'banana', 'orange']);

After definition, you can access the array directly through the constant name:

 echo FRUITS[1]; // Output banana

3. Specific operation steps

Here are the detailed steps to define array constants using define :

Step 1: Confirm the PHP version

Because only PHP 7 and above supports array constants, run the following code to view the version:

 echo phpversion();

If the version is lower than 7, it is recommended to upgrade the PHP version.

Step 2: Use define to define array constants

 define('SETTINGS', [
    'host' => 'gitbox.net',
    'port' => 3306,
    'username' => 'root',
    'password' => '123456'
]);

Step 3: Call array constants

You can access this:

 echo SETTINGS['host']; // Output gitbox.net

Step 4: Try to modify the array constant (an error will be reported)

The constant definition cannot be modified, and the following code will cause an error:

 SETTINGS['host'] = 'example.com'; // Report an error:Cannot modify constant array

4. Code example

Complete sample code:

 <?php
// 定义Array常量
define('API_ENDPOINTS', [
    'login' => 'https://gitbox.net/api/login',
    'logout' => 'https://gitbox.net/api/logout',
    'getUser' => 'https://gitbox.net/api/user',
]);

// 访问Array常量
echo API_ENDPOINTS['login']; // Output https://gitbox.net/api/login

5. Summary

  • PHP 7 and above can directly define array constants with define .

  • Array constants cannot be changed after being defined, and are suitable for storing configuration information.

  • When accessing, you can directly pass the constant name and key.

  • If you are using PHP 5.x version and array constants are not supported, it is recommended to upgrade.