Question
The following PHP code fails when attempting to define a constant containing an array:
define('DEFAULT_ROLES', array('guy', 'development team'));
It appears that constants cannot contain arrays. What is the best way to store a default list of roles without converting the array to a delimited string and calling explode() later?
define('DEFAULT_ROLES', 'guy|development team');
$default = explode('|', DEFAULT_ROLES);
Short Answer
You will learn how PHP constants can store arrays in modern PHP, why older PHP versions could not do this, and when a configuration variable or function is a better choice. You will also see why encoding an array as a delimited string is usually fragile.
Concept
A constant is a named value that should not be reassigned while a program runs. Constants are useful for fixed application settings such as a version number, a directory path, or a small set of default values.
In current PHP, an array can be a constant value:
const DEFAULT_ROLES = ['guy', 'development team'];
This is the clearest solution when the role list is truly fixed.
PHP support depends on the syntax and version:
const NAME = [...];supports array constants starting with PHP 5.6.define('NAME', [...]);supports array values starting with PHP 7.0.- Older PHP versions cannot define an array as a constant. Use a regular configuration variable, a function, or upgrade PHP.
Avoid representing array data as 'guy|development team' unless you are reading a deliberately delimited external format. The delimiter can occur in real data, and every use must remember to split the string back into an array.
Mental Model
Think of a constant as a label permanently attached to a reference card.
- A scalar constant is a card with one value, such as
APP_NAME. - An array constant is a card with a fixed checklist of values, such as
DEFAULT_ROLES.
You may take the checklist and make your own working copy, but the original labeled reference card is not meant to be replaced. A delimited string is like writing the checklist as one sentence and repeatedly cutting it apart whenever you need individual items.
Syntax and Examples
Use const for a modern PHP array constant:
<?php
const DEFAULT_ROLES = ['guy', 'development team'];
foreach (DEFAULT_ROLES as $role) {
echo $role . PHP_EOL;
}
Output:
guy
development team
DEFAULT_ROLES evaluates to an array, so it works directly with array-aware language features such as foreach, in_array(), and count().
For PHP 7.0 or later, define() can also receive an array:
<?php
define('DEFAULT_ROLES', ['guy', 'development team']);
var_dump(DEFAULT_ROLES);
Prefer const when possible because it is concise and clearly communicates a compile-time constant. define() remains useful when the constant name must be calculated dynamically:
<?php
$environment = 'production';
define('APP_MODE_' . strtoupper($environment), true);
For a project that must run on PHP older than 5.6, use a normal variable in a configuration file:
<?php
$defaultRoles = ['guy', 'development team'];
Step by Step Execution
Consider this code:
<?php
const DEFAULT_ROLES = ['guy', 'development team'];
$rolesForNewUser = DEFAULT_ROLES;
$rolesForNewUser[] = 'viewer';
echo count(DEFAULT_ROLES) . PHP_EOL;
echo count($rolesForNewUser) . PHP_EOL;
Step by step:
DEFAULT_ROLESis declared with two strings.$rolesForNewUser = DEFAULT_ROLESreads that array value into a normal variable.$rolesForNewUser[] = 'viewer'adds a role to the variable's array.- The constant is still used as the original default list, so
count(DEFAULT_ROLES)prints2. - The working variable has an extra item, so
count($rolesForNewUser)prints3.
Output:
2
3
The important distinction is that you do not append directly to the constant. Instead, read the default value and modify your own variable.
Real World Use Cases
Array constants are useful for small, fixed collections that are part of the application's code:
- User roles: default roles assigned during account creation.
- Allowed file extensions:
['jpg', 'png', 'webp']for an upload validator. - Supported locales:
['en', 'fr', 'es']in a small application. - Status values:
['pending', 'approved', 'rejected']used by validation rules. - Feature categories: a stable list used by a command-line script.
Use a database, environment variable, or configuration service instead when values must change by deployment, customer, administrator, or runtime state.
Real Codebase Usage
In production code, developers often keep fixed lists close to the class or feature that owns them:
<?php
final class RolePolicy
{
public const DEFAULT_ROLES = ['guy', 'development team'];
public static function isAllowed(string $role): bool
{
return in_array($role, self::DEFAULT_ROLES, true);
}
}
The third argument to in_array() is true, which enables strict comparisons and avoids unexpected matches between values of different types.
A common validation pattern is a guard clause:
<?php
function assignRole(string $role): void
{
if (!in_array($role, RolePolicy::DEFAULT_ROLES, true)) {
throw new InvalidArgumentException('Unsupported role: ' . $role);
}
// Save or assign the validated role.
}
For settings that differ by environment, projects commonly return an array from a PHP configuration file instead of using constants:
<?php
// config/roles.php
return [
'default_roles' => ['guy', 'development team'],
];
The application can load this file once and pass the resulting configuration to the code that needs it.
Common Mistakes
Using a delimiter for structured data
This works only while no role contains |:
$roles = explode('|', 'guy|development team');
It becomes ambiguous if a value is support|on-call. Store an array directly when your data is already in PHP.
Assuming old PHP supports array constants
This is valid only in PHP 5.6 and later:
const DEFAULT_ROLES = ['guy', 'development team'];
If your server runs an older version, use a variable or upgrade. Check the runtime version with:
echo PHP_VERSION;
Trying to modify a constant directly
The following is invalid:
const DEFAULT_ROLES = ['guy'];
DEFAULT_ROLES[] = 'viewer';
Create a normal variable first:
$roles = DEFAULT_ROLES;
$roles[] = 'viewer';
Redefining a constant
A constant name should be declared once. Calling define() again for the same name causes a warning and does not provide a reliable way to change configuration.
Forgetting strict comparisons
Avoid loose matching when validating values:
// Less predictable with mixed types
in_array($value, $allowed);
// Preferred
in_array($value, $allowed, true);
Comparisons
| Approach | Best for | Notes |
|---|---|---|
const DEFAULT_ROLES = [...] | Fixed values in modern PHP | Clear and preferred for PHP 5.6+. |
define('DEFAULT_ROLES', [...]) | Dynamically generated constant names | Array values require PHP 7.0+. |
$defaultRoles = [...] | Configurable or older-PHP code | A variable can be changed or passed into functions. |
return [...] from a config file | Application configuration | Common for framework and application settings. |
| `'a | b'plusexplode()` | Parsing a known external delimited format |
const and define() both create global constants. A class constant is accessed with ClassName::CONSTANT_NAME, while a global constant is accessed by its name:
const APP_NAME = 'Portal';
final class Settings
{
public const TIMEOUT_SECONDS = 30;
}
echo APP_NAME;
echo Settings::TIMEOUT_SECONDS;
Cheat Sheet
// Preferred modern syntax (PHP 5.6+)
const DEFAULT_ROLES = ['guy', 'development team'];
// Read the array
foreach (DEFAULT_ROLES as $role) {
echo $role;
}
// Make a modifiable working copy
$roles = DEFAULT_ROLES;
$roles[] = 'viewer';
// Check membership safely
$isDefault = in_array('guy', DEFAULT_ROLES, true);
// PHP 7.0+ alternative
define('DEFAULT_ROLES', ['guy', 'development team']);
Rules:
- Use
constfor a fixed array when PHP 5.6+ is available. - Use
define()with arrays only on PHP 7.0+. - Do not directly modify or redefine constants.
- Use an array variable or returned config array when the values need to vary.
- Use
in_array($value, $array, true)for strict membership checks.
FAQ
Can a PHP constant contain an array?
Yes. const MY_LIST = ['a', 'b']; is supported from PHP 5.6 onward. define('MY_LIST', ['a', 'b']) is supported from PHP 7.0 onward.
Should I use const or define() for an array constant?
Use const for a normal fixed constant. Use define() mainly when the constant name must be built dynamically at runtime.
Can I add an item to an array constant in PHP?
No. Treat constants as fixed. Assign the constant to a variable and change the variable instead.
Why not store an array as a pipe-separated string?
It requires parsing every time and fails if a value itself contains the delimiter. Use an array when the data originates in PHP.
What should I use on PHP 5.5 or older?
Use a regular array variable or a configuration file that returns an array. Those PHP versions do not support array constants.
Are array constants suitable for database settings?
Usually not. Database hostnames, passwords, and deployment-specific settings should come from secure configuration or environment variables, not source-code constants.
Can class constants be arrays?
Yes, on PHP 5.6 and later. Declare them with const inside the class and access them with ClassName::CONSTANT_NAME.
Mini Project
Description
Build a small role validator for a registration workflow. The application has a fixed list of roles that may be selected by a new user, and invalid role names must be rejected before any data is saved.
Goal
Define a PHP array constant for allowed roles and validate requested roles with a strict membership check.
Requirements
- Declare an array constant containing three allowed roles.
- Create a function that accepts a role name as a string.
- Return
trueonly when the role is in the allowed list. - Use strict comparison when checking the array.
- Demonstrate one allowed role and one rejected role.
Keep learning
Related questions
Are PDO Prepared Statements Enough to Prevent SQL Injection in PHP?
Learn how PDO prepared statements prevent SQL injection in PHP, what they protect, and the mistakes that still leave MySQL apps vulnerable.
Can You Bind an Array to an IN Clause in PHP PDO?
Learn how PDO handles placeholders in IN() clauses, why arrays cannot be bound directly, and the safe PHP pattern to build dynamic queries.
Choosing the Right MySQL Collation for PHP and UTF-8
Learn how MySQL character sets and collations work with PHP, and how to choose a practical UTF-8 setup for web applications.