Turn a string into array with PHP variables

Tags: php arrays eval
By : Jordash
Source: Stackoverflow.com
Question!

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

By : Jordash


Answers

It should be as easy as the following:

preg_match_all('~(\w+)~','[miniTrack, boxTrack]', $matches);
foreach($matches[1] as $var)
{
    print $$var;    
}
By : PyQL


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
}


You can convert your strings to array like this. It may be not ideal but you can use try this.

$string = '[miniTrack, boxTrack]';
$string = str_replace(array('[',']'),array('', '' ), $string);
$array = explode(',',$string);

Here you can iterate your array whatever you want.



This video can help you solving your question :)
By: admin