phparraysloopssuffix

Build an array of static string values -- each with an incremented numeric suffix


I am trying to shorten my coding and I am having a problem here.

I have this very long array list

array(
    stackoverflow1,
    stackoverflow2,
    stackoverflow3,
    stackoverflow4,
    stackoverflow5,
    stackoverflow6
    ...
    stackoverflow100
);

I tried to do something like this

array (
for ($i = 1; $i<100; $i++)
{"stackoverflow".$i,}
);

I tried many ways to clear the syntax error, it just does not work. Is there a way to create a loop within an array?


Solution

  • No, you cannot do what you're trying to do. That is completely unsupported syntax. You cannot mix executable code with array declarations.

    You can, however, declare an empty array, and append items to it:

    $items = array();
    
    for ($i = 1; $i <= 100; ++$i) {
      $item[] = "stackoverflow$i";
    }