2

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

2 Answers 2

9

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Probably the most foolproof way of storing an array. It's barely human-readable, though, so let PHP handle editing it (ie: Don't try "fixing" something with phpMyAdmin).
hey premiso - problem is the array strings already exist as array('aviva'=>'aviva','teacher'=>'teacher'); Basically we'll be adding typing them into phpmyadmin, seqlpro etc.
@daniel: Ewwww. About the only way that's gonna be easily retrievable as an array is using eval -- and then you're opening yourself up to all kinds of crap.
Bad practice. You should really convert it to the serialization. To get it back the only way I would know how would be to either try and utilize this function php.net/manual/en/function.print-r.php#93529 , create your own routine or use eval, which I would highly NOT RECOMMEND using eval given that it can be potentially harmful to your system if bad / unchecked data is passed to it. Better to convert your items to use the proper methods that PHP offer.
3

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.

2 Comments

cheers cags - that works. Just wondering why its not the best way? Its just that all the arrays already exist as strings in the db so would take a bit of time to build an admin that indexes on insert...
Since they already exist as strings then there's really not a good way around it. But it's a massive security risk running eval on your server. I guess this is restricted if you never allow write access to your database from your application. In the future if you wish to store an array in a database, I strongly recommend using serialisation as mentioned by premiso.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.