at 8:12 PM

How to fill constant with array in PHP

Create a constant variable in PHP so easy, we can use keyword define, followed by name of constant and constant value, or we can adding once more argument (boolean true) to identified that is incase-sensitive, like this:

define ('NAME', 'value of constant');
echo NAME; //output value of constant;
echo Name; //output value of constant with somes notice

define ('OK', 'its ok', true);
echo OK; // output its ok.
echo oK; //output its ok, there are no problem here.



Based on PHP Manual we can't define a constant variable with value as array, yes we can't do that.
But we can make a some tricky so a constant can be use as an array with serialize and when we want to used it just reverse with unserialize.

$arr = array ('one'=>'satu', 'two'=>'dua');

// create a constant 
define ('EN2ID', serialize($arr));

// and we use now
foreach (unserialize(EN2ID) as $key => $val) {
      echo '"', $key, '" in Indonesia is ', $val, "\"\n";

}

Yeah that is not array but string, i dont care.. :)


Tulis Komentar dengan akun Facebook Anda.

0 comments:

Post a Comment