Defining Arrays as Constants in PHP

Today I was re-factoring code on one of my online games websites. I try to make my sites as modular as possible, using a lot of constants that are extracted into a config.php file.

After trying to extract an array into a constant, I was getting the following warning:
Constants may only evaluate to scalar values

It turns out that define() supports only definitions that include scalar values, and not arrays. The methods I thought of for circumventing this restriction include:

  1. Define your array as a delimited string, then split it afterwards using explode().
  2. Do not use define(), but rather create a database table and select the values with SQL. This still achieves the component of modularity, but it involves running an extra query.
  3. Don’t make it a constant and just hard code the array.

Leave a Reply

Your email address will not be published. Required fields are marked *