0

I have a string like that :

$str = "array (
   'from' => 'OK',
   'to' => 'OK',
   array (
      'id' => 204847
   ),
)"

How could I create the array that matches ? Or how could I get the id ?

4
  • 1
    how did you get such a string in the first place? Commented Nov 14, 2012 at 10:43
  • This is going to take you into unwanted territory. Can you change the input to be in a recognised interchange format such as JSON or XML? Commented Nov 14, 2012 at 10:43
  • If you store the data yourself make sure you use php.net/manual/en/function.serialize.php after that you can use unserialize Commented Nov 14, 2012 at 10:43
  • 1
    look at eval e.g. eval('$myarray='.$str.';'); Commented Nov 14, 2012 at 10:44

3 Answers 3

3

If this string is not user input the easiest way would be to use eval.

eval('$myArray = '.$str.';');

Important note from the documentation:

The eval() language construct is very dangerous because it allows execution of arbitrary PHP code. Its use thus is discouraged. If you have carefully verified that there is no other option than to use this construct, pay special attention not to pass any user provided data into it without properly validating it beforehand.

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

3 Comments

add a semi-colon on the end too
This post requires a big frakoff warning attached to it.
Please note the use of single quotes, so its a literal string.
2

I'm going to break the "answer the question as posed" mould because eval is extremely dangerous and I shall not even come close to recommending its use.

Instead, change your string to a recognised interchange format, such as JSON or even XML. Or PHP's native serialisation format...

Comments

2

You could use PHP's eval() function thought you need to be CERTAIN that this string is trusted.. even then I am loathe to recommend it:

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

Warnings: When is eval evil in php? for why it is evil

2 Comments

Hmm, just discovered that "loathe" rather than "loathed" is correct, here, moments before editing your post. Thanks!
It will make me loathed, but I loathe myself :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.