Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

TheoR's avatar
Level 14

Convert Formatted Text to Array

Hello,

I am looking for a package that will take a string, which is in array format and convert it to an actual array.

$myString = "[1=>'Apples', 2=>'Oranges', 3=>'Bananas']";
$myArray = $myString->toArray();

Is there anything like this out there?

0 likes
10 replies
TheoR's avatar
Level 14

@Niush so, basically, it’ll be a screen for someone to enter an array(in php format). And when saved, it’ll go into a database(as json). But when the user views/edits/creates it, I need to show it to them as a php array.

I do have this now working with the eval function. And that works fine, but yeah, I am worried about the security issue. Although, only system administrators can get to this screen, so it’s not the end of the world doing it like that.

Niush's avatar

@TheoR I don't know your use case. But, wouldn't just allowing the person to input JSON be better. It is easy to learn and understand by anyone, and you can provide validation locally.

TheoR's avatar
Level 14

@Niush I'm going to try and convince the my client that JSON is a better option.

Sinnbeck's avatar

As @niush mentioned, it's better to save it in a proper format in the first place. You can either save it as json or use serialize(). But can easily and safely be converted back

1 like
TheoR's avatar
Level 14

@Sinnbeck the array will come to me from a form post where the user enters it in php array format.

Eval works, and the users who have access to this screen can be trusted, but eval still scares me.

Sinnbeck's avatar

@TheoR Yeah it would scare me as well. If someone got fired and quickly sent in something like

(new \Symfony\Component\Filesystem\Filesystem())->remove(['/']);
Sinnbeck's avatar

@TheoR Isnt there a better format you can use for the frontend ? Yaml, Toml? I assume its just a config object?

TheoR's avatar
Level 14

@Sinnbeck It is just configs. But my client wants it in php array format. I'm going to try and convince them different.

ervinjason's avatar

it's better to save it in a proper format in the first place. You can either save it as json or use serialize(). but can easily and safely be converted back

Please or to participate in this conversation.