0

How can i convert this string

$str = "array('3'=>'wwm','1'=>'wom')";

to real php associative array...

3
  • How do you get such a string in the first place? Commented Apr 24, 2013 at 13:08
  • I am sending this string to database ... and now i want to use it after retrieving from database Commented Apr 24, 2013 at 13:09
  • 2
    Do NOT do that. Use ch2.php.net/serialize instead. Commented Apr 24, 2013 at 13:12

3 Answers 3

5

It's simple but REALLY INSECURE

$str = "array('3'=>'www.tension.com','1'=>'www.seomeuo.com','requestedBy'=>'1')";
eval("\$array = $str;");

You never should use this approach, there another ways to do it like: serialize() and unserialize()

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

5 Comments

serialization is the better choice
Parse error: syntax error, unexpected $end in /home/user/test.php(5) : eval()'d code on line 1
Fixed, first $ sign should be escaped with \
Not fixed. Still get: Parse error: syntax error, unexpected $end in /home/user/test.php(5) : eval()'d code on line 1 – hek2mgl 11
Yes, now it's working, after you've added to the ;. Note that the ; is essential
3

You can use the eval() function for that:

$str = "array('3'=>'wwm','1'=>'wom')";

eval("\$a=$str;");

var_dump($a);

However using eval() in your code is considered to be risky and you should not use it. Try to use serialize(), unserialize() instead.

Comments

1

First of all. Do not use eval. It is Evil! http://af-design.com/blog/2010/10/20/phps-eval-is-evil/

Secondly. The simple solution would not to be using this string but simply to use "serialize" when you put it in the DB and unserialize when you pull it out. You are storing a very unusual format.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.