Monday, August 26, 2013

How to set global constants containing arrays using Codeigniter?

You can use Codeigniter's constants file to store global arrays which can be used in multiple controllers or any where within your codeigniter's project scope.
Problem: Apparently, constants can't hold arrays.
Solution: You can serialize your array and then put it into the constant.
For example,
# define constant, serialize array
define ("FRUITS", serialize (array ("apple", "cherry", "banana")));

# use it
$my_fruits = unserialize (FRUITS);
You can store it as a JSON string in a constant. And application point of view, JSON can be useful in other cases.
define ("FRUITS", json_encode(array ("apple", "cherry", "banana")));    
$fruits = json_decode (FRUITS);    
It may exists other efficient ways to store global arrays in Codeigniter. Suggestions will be appreciated. :)