natli
natli

Reputation: 3822

Convert plain text to array

If I get the following text string from mysql (or whatever) how can I convert it to an actual array using PHP?

array("foo" => "bar","honey" => "pops")

I know I can save an array in a serialized state, but that's exactly what I'm trying to avoid here.

Upvotes: 0

Views: 1114

Answers (3)

Baba
Baba

Reputation: 95121

Use eval but it is too dangerous .... I DON'T ADVICE YOU USE SUCH

$string = '$array = array("foo" => "bar","honey" => "pops");' ;
eval($string);
var_dump($array);

Output

array(2) {
    ["foo"]=>
    string(3) "bar"
    ["honey"]=>
    string(4) "pops"
}

Recommendation

use standard formats such as

JSON http://php.net/manual/en/book.json.php

XML http://php.net/manual/en/book.simplexml.php

Serialized PHP http://php.net/manual/en/function.serialize.php

Upvotes: 1

gen_Eric
gen_Eric

Reputation: 227270

The answer is "don't do this". Never put PHP code in your database. The database is for data, not code.

The correct way is to store a serialized array (not sure why you'd want to avoid that).

Upvotes: 1

Stelian Matei
Stelian Matei

Reputation: 11623

You could use the eval function:

http://php.net/manual/en/function.eval.php

Try something like this:

$my_string = 'array("foo" => "bar","honey" => "pops")';

eval("\$result=$my_string;");

Upvotes: 0

Related Questions