0

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?

0

3 Answers 3

2

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";
}
Sign up to request clarification or add additional context in comments.

Comments

1
<?php

    $arr = array();

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

    var_dump($arr);

?>

1 Comment

Please don't dump code-only answers into the site. The code is far less important than the explanation that is supposed to go with it.
0

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',
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.