2011-06-05

Tips o Truco para guarda Array en una constante con PHP

Hay dos forma muy simple para guarda un Array dentro de una constante.

1- Por medio de json_decode() 

// String json de un array asociativa
define('FORM_ARRAY_JSON_MODELOS_SEXO','{"m":"Masculino","f":"Femenino"}');
// Generamos el array con el string que esta en la constante
var_dump( json_decode(FORM_ARRAY_JSON_MODELOS_SEXO,TRUE) );
//echo $this->Form->input('sexo', array('type'=>'select', 'options'=> json_decode(FORM_ARRAY_JSON_MODELOS_SEXO,TRUE)));
view raw gistfile1.php hosted with ❤ by GitHub


2- Por medio de eval(), var_export()

// Array asociativa
define('FORM_ARRAY_JSON_MODELOS_SEXO', 'return ' . var_export(array('m'=>'Masculino','f'=>'Femenino'), 1) . ';');
// Generamos el array con el string que esta en la constante
var_dump( eval(FORM_ARRAY_JSON_MODELOS_SEXO) );
//echo $this->Form->input('sexo', array('type'=>'select', 'options'=>eval(FORM_ARRAY_JSON_MODELOS_SEXO)));
view raw gistfile1.php hosted with ❤ by GitHub


3- Por medio serialize() y unserialize()

// Array asociativa
define('FORM_ARRAY_MODELOS_SEXO', serialize(array('m'=>"Masculino",'f'=>"Femenino")) );
// Generamos el array con el string que esta en la constante
var_dump( unserialize(FORM_ARRAY_MODELOS_SEXO) );
//echo $this->Form->input('sexo', array('type'=>'select', 'options'=>unserialize(FORM_ARRAY_MODELOS_SEXO)));
view raw gistfile1.php hosted with ❤ by GitHub


Para mi gusto por seguridad y simpleza la opción 1 o 3  son las mejores de implementar dentro de codigo PHP.

No hay comentarios: