Define Array as Value of Constants in PHP

PHP

Read {count} times since 2020

Constants are something that is needed for every computer languages. In PHP, too you can set constants. But you can only set string values which is a pity, because if you want to set arrays for making it easy for obtaining multiple values, you can’t do it. In this case, we explore the unimaginable possibilities of programming languages. As like any other language, PHP too has a secret weapon to accomplish this task.

Long Things Short

We’ll use PHP’s serialize function to make an Array look like string and this string is defined as the constant value. For making the string back to the original Array, we’ll use unserialize function. It’s very easy and works in both **PHP 4 **and PHP 5.

The Array

We make the array first. Here’s the array containing some sample values :

$array = array(
 "Subin" => "Siby",
 "John" => "Resig",
 "Larry" => "Page",
 "Coding" => "Horror"
);

As you can see, the index is the first name of persons and the values are the last name of the persons.

Serialize

Now, we serialize the Array and put it in to a variable :

$serialized = serialize($array);

The above variable $serialized will now contain a string something like this :

a:4:{s:5:"Subin";s:4:"Siby";s:4:"John";s:5:"Resig";s:5:"Larry";s:4:"Page";s:6:"Coding";s:6:"Horror";}

You can see that the index and values of the array are in the above serialized output. We’ll make this as the value to be set for constant.

Set Constant

We define the constant :

define("MyArray", $serialized);

Now, you can access the string from anywhere, just like this :

echo MyArray;

Get back the Array

To get back the array, we unserialize the string and an array value is returned :

$BackArray = unserialize(MyArray);

unserialize() will return values according to the value first serialized. So, if you serialize a string the return value of the unserialize function will be a string. This applies to all cases like Arrays, booleans, integers etc… In this case, we can directly get values from the array now :

echo $BackArray["Larry"]; // Prints Page

And now you know how setting Array as Constant values work. Hope you understood the procedure. If you have a problem with this, you can ask by the comments or SO.