Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array stored as string back into array?

Tags:

arrays

string

php

just trying to add some setting for the admin in a database entry.

i've saved;

array('aviva'=>'aviva','teacher'=>'teacher');

into the field 'fullPara' but can't seem to get it back into an array? Just spits it out as a string and i've tried eval but not sure where to go from here?

echo $userTypes['fullPara']; // spits out array('aviva'=>'aviva','teacher'=>'teacher');

any pointers welcome!

best, Dan

like image 912
v3nt Avatar asked Mar 16 '26 00:03

v3nt


2 Answers

You want to look into the serialize() and unserialize() functions PHP offers.

Here is an example:

$array = array('1', '3', '4');
$s_array = serialize($array);
// insert that into the db.


// later on when fetching.
$array = unserialize($array_from_db); 
print_r($array); // viola

EDIT

I do NOT recommend this but here is how you would convert it to an array using eval:

eval("\$array = " . $data_from_Db);
print_r($array);

Should get you what you were after.

like image 195
Jim Avatar answered Mar 18 '26 13:03

Jim


If you already have a string of "array('aviva'=>'aviva','teacher'=>'teacher'); " and you wish to turn it into an array, this should work...

$str = "array('aviva'=>'aviva','teacher'=>'teacher');"; 
eval("\$foo = $str");
var_dump($foo);

It's really not the best way of doing it though.

like image 41
Peter O'Callaghan Avatar answered Mar 18 '26 13:03

Peter O'Callaghan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!