0

I have a string (something like var_dump) and need to convert it to an array. I can use explode and str_replace ... but i need to know is there any other or better solution for this issue or not. string is line by line ...

example string:

$myString = "something => somevalue
anotherthing => somevalue
A => B
X => Z";

need to convert to:

$myArray = array(something => somevalue,anotherthing => somevalue,A => B,X => Z");
2
  • explode it by newline, then explode each line by arrow. explode Commented Sep 28, 2020 at 1:19
  • 2
    It would be better if you used a format that's designed to be parsed, like JSON. Commented Sep 28, 2020 at 1:20

2 Answers 2

3

A few exotic options.

INI parser:

$array = parse_ini_string(str_replace('=>', '=', $string));

URL parser:

parse_str(str_replace(' => ', '=', str_replace(PHP_EOL, '&', $string)), $array);

RegExp:

preg_match_all('/(.*) \=\> (.*)/', $string, $matches);

$array = array_combine($matches[1], $matches[2]);
Sign up to request clarification or add additional context in comments.

Comments

2

You can just use a nested explode:

$myString = "something => somevalue
anotherthing => somevalue
A => B
X => Z";

$myArray = array();
foreach (explode(PHP_EOL, $myString) as $line) {
    list($key, $value) = explode(' => ', $line);
    $myArray[$key] = $value;
}
print_r($myArray);

Output:

Array
(
    [something] => somevalue
    [anotherthing] => somevalue
    [A] => B
    [X] => Z
)

Demo on 3v4l.org

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.