Pierrick Rambaud
Pierrick Rambaud

Reputation: 2434

use foreach on declared but empty array

To limit the use of [xx] in my code I would like to do something C/C++ style :

$nbItem = 30;
items = array($nbItem);

foreach ($items as $i => $item){
    $item = new Entity();
    $item->setToto();
    // do other stuff
}

Of course it didn't work, is there a typo or is just impossible in php ?

Note

I know how to do the same with a for ($i ....) loop so my question is specifically on foreach

Upvotes: 0

Views: 68

Answers (3)

axiac
axiac

Reputation: 72256

There are two things you have to pay attention regarding the code you posted.

array(30) does not produce an array with 30 items but one array having 30 as its only element.
For an array with 30 items you can use array_fill().

foreach ($items as $i => $item) -- $item is not a reference but a copy of an element of the array.
You then store something else in $item ($item = new Entity();) and the array seems to be used only to count to 30.

If your intention is to use the array only to count to 30 then the easiest way is to generate the array using range():

foreach (range(1, 30) as $i) {
  $item = new Entity();
  $item->setToto();
}

Upvotes: 0

Danial Shabbir
Danial Shabbir

Reputation: 650

You can use array_fill method. e.g in your code

$nbItem = 30;
items = array_fill(0,$nbItem,0);

foreach ($items as $i => $item){
    $item = new Entity();
    $item->setToto();
    // do other stuff
}

In your code, you are trying to push the 30 into array which is at 0 index, ultimately it has a size of 1

If you dont want to assign 0 to every index you can use range e.g

$nbItem = 30;
items = range(0,$nbItem);

foreach ($items as $i => $item){
    $item = new Entity();
    $item->setToto();
    // do other stuff
}

i would recommend this solution cz its neater

Upvotes: 2

kaczmen
kaczmen

Reputation: 528

There is no way to declare array size as you suggested. If you MUST use foreach you can try this way:

$items = array_fill(0, $nbItem, null);

foreach($items as $i => &$item) {
    $item = new Entity();
    $item->setToto();
    // do other stuff
}

But I strongly discourage you to use this solution. Just do it in a for loop:

$items = [];

for($i = 0; $i < $nbItem; $i++) {
    $item = new Entity();
    $item->setToto();
    // do other stuff

    $items[] = $item;
}

Upvotes: 0

Related Questions