1

I am trying to find a way to transform a string type variable into an array type variable. To be more precise, what i am looking for is the change this (example):

$v = "['1', 'a', ['2', 'b', ['3'], 'c']]";

note that this is not a json-formatted string. into this:

$v = ['1', 'a', ['2', 'b', ['3'], 'c']];

Note the double-quotes in the first example, $v is a string, not an array, which is the desired effect.

5
  • Second hint: parse Commented Apr 22, 2016 at 11:47
  • Possible duplicate of How to convert JSON string to array Commented Apr 22, 2016 at 11:48
  • 2
    Single quotes aren't valid in JSON, so that won't help here. If you've got PHP array syntax in a string, you'll need to use eval(), as horrible as that is. Commented Apr 22, 2016 at 11:49
  • That does not have a valid json schema Commented Apr 22, 2016 at 11:50
  • @iainn you're right, json parse didn't help me at all, and simply using eval on it won't work either. i presume it needs some complex combination of parsing and eval Commented Apr 22, 2016 at 11:50

3 Answers 3

3

Simple solution using str_replace(to prepare for decoding) and json_decode functions:

$v = "['1', 'a', ['2', 'b', ['3'], 'c']]";
$converted = json_decode(str_replace("'",'"',$v));

print_r($converted);

The output:

Array
(
    [0] => 1
    [1] => a
    [2] => Array
        (
            [0] => 2
            [1] => b
            [2] => Array
                (
                    [0] => 3
                )

            [3] => c
        )    
)
Sign up to request clarification or add additional context in comments.

Comments

2
$v = "['1', 'a', ['2', 'b', ['3'], 'c']]";

eval("\$v = $v;");

var_dump($v);

PS: make sure $v string doesn't contain unexpected code.

2 Comments

thank you for your answer! the code provided works, but i choose to use Romans' solution to avoid using the eval function
You're welcome, and you're right about preferring the json_decode solution over eval.
1

This should work:

$json = "['1', 'a', ['2', 'b', ['3'], 'c']]";
$json = str_replace("'",'"',$json);
$result_array = json_decode($json); // This is your array

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.