Define array as constant in PHP

by  
Share:
php

In PHP versions below 7, arrays cannot be defined as constants, You can only define constants with scalar (bool, int, float, or string) expressions. Constants are unchangeable once they have been defined.

UPDATE: If you are on PHP7 or above just define array as constant directly. 

Take a look at the code below.

<?php
define('ANIMALS', array(
'dog',
'cat',
'bird'
));

echo ANIMALS[1]; // outputs "cat"
?>

In a version lower than PHP7, adding arrays as constants result in an error. Here’s an alternative approach to defining array in a constant.

Serialize proves to be very useful for storing or passing PHP values around without losing their type and structure. You can read more about it here.

<?php
define("ANIMALS", serialize(array("dog","cat", "bird")));
?>

To print the value of the constant that you just serialized. By unserialize() the variable, the value will be returned as an array.

<?php
$st_options = unserialize (ANIMALS);
print_r($st_options);
?>

Get the latest updates directly in your inbox for FREE: Subscribe here

Share your feedback / let me know your doubts regarding this tutorial in the comment box given below.

Share:
Hasan

Shahrukh Khan (Hasan)

A software engineer who's a die-hard coder, blogger, dreamer and mentor with years of expertise in web development. Know more...

Related Posts

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.