Define and Access array in constants PHP

2.8K views
no comments
17 Oct 2015 11:39 pm

PHP 5.5 and in older version constants cannot store directly array

In this matter we are allowing to upload limited file’s extensions and this is not good codding practice to defined allowed extensions and check every file on uploading code because we needs to store allowed extensions in a single place for easily modify them.

Code of store and get array from constant

Through a trick define array and convert into a json string with json_encode function

define('allow_ext',json_encode(array('jpeg','jpg','png','mp4','txt','doc','xls')));

Get stored array data from constant

Here is contacts allow_ext will return json string and then convert it into array with json_decode function

$allow_ext = json_decode(allow_ext,true);

PHP 5.6+ easily store and access array data from constant

const allow_ext = ['jpeg','jpg','png','mp4','txt','doc','xls'];

NOTE:Your Email Address will be not shown and please do not add spamming comments because here is REL="NOFOLLOW" on your links and comments also moderated shown.
<code>Put html css or any language code under this tag</code>