user1761160
user1761160

Reputation: 281

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?

Upvotes: 0

Views: 64

Answers (3)

mickmackusa
mickmackusa

Reputation: 48041

You can prepend an array of ascending numbers without an explicit loop. Pass your range of integers to substr_replace() then nominate the string stackoverflow as the text to prepend to each value of the array. By using 0 as the 3rd and 4th parameters, you state that the string should be injected at the first offset/position of each value and that no characters should be consumed by that injection.

Code: (Demo)

var_export(
    substr_replace(range(1, 10), 'stackoverflow', 0, 0)
);

Output:

array (
  0 => 'stackoverflow1',
  1 => 'stackoverflow2',
  2 => 'stackoverflow3',
  3 => 'stackoverflow4',
  4 => 'stackoverflow5',
  5 => 'stackoverflow6',
  6 => 'stackoverflow7',
  7 => 'stackoverflow8',
  8 => 'stackoverflow9',
  9 => 'stackoverflow10',
)

Upvotes: 0

Travis
Travis

Reputation: 5071

<?php

    $arr = array();

    for($i=1; $i<100; $i++){
        $arr[] = "stackoverflow".$i;
    }

    var_dump($arr);

?>

Upvotes: 1

user229044
user229044

Reputation: 239501

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";
}

Upvotes: 2

Related Questions