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?

2
  • how/where do you get this string? Commented Apr 29, 2016 at 9:34
  • Seriously, I would consider changing something in your application, if there is a case where you need to do this. Commented Apr 29, 2016 at 22:04

3 Answers 3

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?

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

2 Comments

Thanks for the fast AND correct reply! I forgot that eval function ;)
Careful using eval though never ever use it with user input ;)
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)

Comments

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] => #
)*/

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.