phparraysconstantsscalar

PHP Constants Containing Arrays?


This failed:

 define('DEFAULT_ROLES', array('guy', 'development team'));

Apparently, constants can't hold arrays. What is the best way to get around this?

define('DEFAULT_ROLES', 'guy|development team');

//...

$default = explode('|', DEFAULT_ROLES);

This seems like unnecessary effort.


Solution

  • PHP 5.6+ introduced const arrays - see Andrea Faulds' answer.

    You can also serialize your array and then put it into the constant:

    # define constant, serialize array
    define ("FRUITS", serialize (array ("apple", "cherry", "banana")));
    
    # use it
    $my_fruits = unserialize (FRUITS);