Jordash Jordash - 2 months ago 10
PHP Question

Turn a string into array with PHP variables

I have a string like this:

$string = '[miniTrack, boxTrack]'


I want to turn it into an array of variables like this:

$array = [$miniTrack, $boxTrack]
;

So that I can perform loops and iterations through the variable. And access the variables they are referencing.

I tried eval but I can't figure out how to convert it to a PHP Variable.

I KNOW THAT THIS IS NOT IDEAL, THE STRUCTURE OF THE DATABASE THIS IS PULLING FROM CAN'T BE ADJUSTED UNFORTUNATELY

Answer

Your question starts unusually, because you show an array containing a single string that is comma-separated, rather than an array of individual strings.

You could try something like the following:

$arr = [];
$string = ['miniTrack, boxtrack'];
//split the one string into an array, trimming spaces
$vars= array_map('trim', explode(',', $string[0]));
foreach($vars as $var) {
    $arr[] = $var; //add the var to the array 
}

print_r($arr);

Array
(
    [0] => miniTrack
    [1] => boxtrack
)

And if you need to create a variable for each item, you can create "variable variables":

foreach($vars as $var) {
    $my_var = $$var; //variable variable
}
Comments