variable variables bad practice to use?

血红的双手。 提交于 2020-01-05 10:14:42

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/17343949/variable-variables-bad-practice-to-use

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!