0

I've the following variable that is dinamically created:

$var = "'a'=>'123', 'b'=>'456'";

I use it to populate an array:

$array=array($var);

I can't do $array=array('a'=>'123', 'b'=>'456') because $var is always different.

So it shows me:

Array
(
    [0] => 'a'=>'123', 'b'=>'456'
)

This is wrong, 'cause I need to get:

Array
(
    [a] => 123
    [b] => 456
)

What is wrong on my code? Thanks in advance.

2
  • 4
    If for whatever reason you must generate a string as $var in the first place. Consider generating it as a JSON string - {"a":"123", "b":"456"} as you can then use standard JSON methods to convert it. Commented Aug 17, 2019 at 15:43
  • 1
    If you have control over the creation of the dynamic string, you should use JSON encoding to pass the values. Then it’s as simple as json_encode() and json_decode() Commented Aug 17, 2019 at 15:57

1 Answer 1

1

Ideally you should just leverage PHP's syntax to populate an associative array, something like this:

$array = [];
$array['a'] = '123';
$array['b'] = '456';

However, you could actually write a script which parses your input to generate an associate array:

$var = "'a'=>'123', 'b'=>'456'";
preg_match_all ("/'([^']+)'=>'([^']+)'/", $var, $matches);
$array = [];
for ($i=0; $i < count($matches[0]); $i++) {
    $array[$matches[1][$i]] = $matches[2][$i];
}
print_r($array);

This prints:

Array
(
    [a] => 123
    [b] => 456
)
Sign up to request clarification or add additional context in comments.

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.