views:

80

answers:

3

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

To prevent error "Only variables can 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?

+4  A: 

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.

halfdan
how to create an empty variable? without =
Happy
What's the point of an empty variable? You don't need to explicitly declare variables in PHP. Just use the variable when you assign something to it.
halfdan
+1  A: 

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

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

pedrorezende
A: 

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.

matsolof