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

mvnobrega's avatar

Convert string to array [ SOLVED ]

I have strings stored in my database in array format, but they are strings, for example:

['Bette Midler', 'Sarah Jessica Parker', 'Kathy Najimy', 'Whitney Peak', 'Belissa Escobedo', 'Lilia Buckingham', 'Froy Gutierrez', 'Sam Richardson', 'Doug Jones', 'Tony Hale', 'Taylor Henderson', 'Nina Kitchen', 'Juju Journey Brener', 'Thomas Fitzgerald', 'Brett Cramp', 'Kim Niemi', 'Alison Weller', 'Holly Cinnamon']

I need to loop through this as if it were an array, so I'm trying this:

@foreach(json_decode($filme->elenco_principal) as $e)
               {{$e}}
@endforeach

But I get this error : foreach() argument must be of type array|object, null given

And the same happens if I try with json_encode()

What is the simplest and most practical way to get this data as an array and loop through it?

0 likes
2 replies
Tray2's avatar

The best way is to make a pivot where you connect the movie and the actor. The json_decode returns null since it's not properly formed json.

The string you store in the database must look like this

$test = '{ "actors": ["Bette Midler", "Sarah Jessica Parker", "Kathy Najimy", "Whitney Peak", "Belissa Escobedo", "Lilia Buckingham", "Froy Gutierrez"]}';

$t1 = json_decode($test);

$t1->actors;

I suggest reading this post.

https://tray2.se/posts/database-design

1 like
SilenceBringer's avatar
Level 55

@mvnobrega strange format for storing in the database. But you can parse it as

@foreach(explode(', ', trim($filme->elenco_principal, '[]')) as $e)
               {{$e}}
@endforeach
1 like

Please or to participate in this conversation.