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 ?

PJ Bergeron
  • 2,788
  • 4
  • 25
  • 42

3 Answers3

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.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Leri
  • 12,367
  • 7
  • 43
  • 60
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

Community
  • 1
  • 1
Martin Lyne
  • 3,157
  • 2
  • 22
  • 28
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...

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055