开发者

Unique variables inside foreach()

Trying to create a variable with unique name for each $item.

To prevent error "Only variables can 开发者_Go百科be passed by reference".


If there are 5 items in array $items, we should get 5 unique variables:

$item_name_1;
$item_name_2;
$item_name_3;
$item_name_4;
$item_name_5;

All of them should be empty.

What is a true solution for this?


You can dynamically create variable names doing the following:

$item_name_{$count} = $whatever;

I must warn you though, this is absolutely bad style and I've never seen a good reason to use this. In almost every use case an array would be the better solution.


Well, I guess that you can use $item_name_{$count} = "lorem ipsum"; for it

... But won't be better to use an array?


I'm not sure I understand what you want to do, so this may be completely wrong. Anyway, if what you want is an array with empty values you can use this code:

<?php
$arr = array_fill(0, 3, '');
var_export($arr) // array ( 0 => '', 1 => '', 2 => '', 3 => '', )
?>

See array_fill for more information.

If this is the wrong answer, please clarify what you mean. I may be able to help you.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜