0

I'm developing a PHP app and I have a problem by converting a string array into an object array. I tried to force casting my string into an array by using (array), but it won't works. Here is my string (debug):

string '['method'=>'post','action'=>'#']' (length=32)

As you can see, it's a perfect array into a string and i want to convert that string.

My question is simple, does PHP has a function to convert directly a string into an array (I think no) or i have to convert my string by using explode?

houceni
  • 23
  • 4

3 Answers3

0

Here is how you define an array. But before writing code, please take a look at manuels

$arrayName = array('method' => 'post', 'action' => '#');

The output will read

array (size=2)
  'method' => string 'post' (length=4)
  'action' => string '#' (length=1)
ilhnctn
  • 2,210
  • 3
  • 23
  • 41
0

From php 5.4 you can simply eval: eval("\$f=['method'=>'post','action'=>'#'];"); var_dump($f);

For olders you have to fix the string a bit, change the 1st "[" to "array(" and the last "]" to ")".

The question is a bit duplicate of How to create an array from output of var_dump in PHP?

Community
  • 1
  • 1
Zedorg
  • 170
  • 1
  • 5
0

You can use preg_split and foreach() to make this work:

$str = "['method'=>'post','action'=>'#']";

$splitArray = preg_split("/[,']+/", $str);
foreach ($splitArray as $k => $val) {
  if ($val == '=>') {
    $newArr[$splitArray[$k - 1]] =  $splitArray[$k + 1];
  }
}

var_dump($newArr);
/*newArr
Array
(
  [method] => post
  [action] => #
)*/
jitendrapurohit
  • 9,435
  • 2
  • 28
  • 39