Declaring a Constant Array in PHP
December 08, 2014

Introduction

If you want to declare an array as a constant in PHP, you need to look further than what PHP provides as standard. Technically, if you look at PHP's Constants Syntax, it's not possible to define an array as constant, except from PHP 5.6 onwards. As of this writing, PHP 5.6 is still not widely available, and hence here's another quick and simple solution.

To come up with the code below, we looked at many threads on Stack Overflow. This one is the most popular and offers many solutions. The result of our research is this little code snippet below. Keep in mind that we have tried to use the "const" keyword instead of the "define" method presented below and we found out that "const" doesn't work for this trick.

Happy coding.

Example Code Snippet of Constant PHP Arrays


<?php

//Define PHP array constant using JSON encode
define("FRUITS", json_encode(array(
    "Watermelon", 
    "Strawberries",
    "Pomegranate",
    "Blackberry",
)));

//Use array constant in PHP by using JSON decode
$fruits = json_decode(FRUITS);
var_dump($fruits);

Serialize and UnSerialize

The solution presented in this Stack Overflow post uses PHP's "serialize" and "unserialize" functions to define constant PHP arrays.

We prefer the usage of PHP's JSON encode and decode as they are safer. Let me explain why. Technically, in this context, they are both similar as the input given to "unserialize" is a constant. However, in general, "unserialize" can be used to handle any variable and if given user input the "unserialize" function can be maliciously used to hijack your application or website unless you cleanup the input before passing it to "unserialize". For this reason, we prefer the usage of the safer JSON decode method as it can't be exploited in a similar fashion to "unserialize".

Declare a Constant Array in PHP 5.6 and Newer

From PHP 5.6 onwards, it is also possible to define an array constant. For example:


<?php
const FRUITS = array(
    "Watermelon", 
    "Strawberries",
    "Pomegranate",
    "Blackberry",
);
var_dump(FRUITS);


Development PHP Open Source

Share this post


Written by
Mario Awad

Founder of SOFTKUBE, lead developer, and getting things done addict. Passionate about open source, user interface design, business development, and the tech world.

More about Mario Awad


About
SOFTKUBE

A small team of experts developing simple, usable, and high-quality web solutions. We blog about business, entrepreneurship, web development, and technology.

More about us


Recent Posts

Shared Office Space for Rent in Dekwaneh, Beirut, Lebanon as a Professional Work Environment

Transform your Custom PHP Script into a Globally Available CLI Command

Using Google for Live Unit Conversions

Declaring a Constant Array in PHP

View all posts


All Posts Categories

Business CLI Development Downloads Drupal Email Google Apps Multilingualism Open Source PHP Security SEO Technology Windows Zend Framework