Question

I have just read the post is it bad practice to use variable variables in php in the following fashion? explaining why they are bad to use in with classes however, i have to create dynamic variables to be sorted

for example:

$array =
array(
 array("Line 1","Line 2","Line 3"),
 array("Line 1","Line 2","Line 3"),
 array("Line 1","Line 2","Line 3"),
)
$i = 1;
foreach($array as $item){
 $string = "Item".$i;
 $$string = $item[0]."some code".$item[1]."some code".$item[2]."some code";
}

i know that there will only ever be 3 array values in each secondary array and there will only ever be 3 arrays.

is there a way to achieve this using "better practice" code? or a simpler way which i have overlooked?

thank you for your time in advance

Was it helpful?

Solution

This should do it just fine:

$newArray = array_map(function (array $item) {
    return $item[0]."some code".$item[1]."some code".$item[2]."some code";
}, $array);

var_dump($newArray);

I don't see where separate variables are needed at all.

If you just continuously number variables dynamically ($item1, $item2 etc.), you're trying to hold a dynamic number of elements. That's exactly what arrays are for: $items[0], $items[1] etc.

OTHER TIPS

I certainly wouldn't use "variable variables". There once was a time that I thought they were quite cool, but then not long after I realized that they are just misplaced arrays of data. Using variable variables remove any possibility of using the vastly powerful native PHP array_ functions. I recommend that you stay away from them as much as possible.

Furthermore, you IDE is going to have a much harder time tracking your variably named variables and you'll see a bunch of false-positive warnings in your IDE that variables are being used without being closed.

I would probably map your input array (like @deceze mentioned), but vsprintf() is a good technique to avoid concatenating the strings.

Code: (Demo)

$array = [
    ["Line 1", "Line 2", "Line 3"],
    ["Line 4", "Line 5", "Line 6"],
    ["Line 7", "Line 8", "Line 9"],
];

var_export(
    array_map(
        fn($row) => vsprintf('%s some code %s some code %s some code', $row),
        $array
    )
);

Output:

array (
  0 => 'Line 1 some code Line 2 some code Line 3 some code',
  1 => 'Line 4 some code Line 5 some code Line 6 some code',
  2 => 'Line 7 some code Line 8 some code Line 9 some code',
)

Then (assuming your save the output as a variable instead of printing) whenever you want to re-access this data, you can cleanly use a basic loop.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top