Filling PHP array with "for" loop

1.1k views Asked by At

I'm trying to populate an array in PHP as following :

<?php

$maxPages = 20;

for ($i = 0; $i <= $maxPages; $i++) {

    $url = 'http://127.0.0.1/?page='.$i;

    $targets =  array(
            $url => array(
                    CURLOPT_TIMEOUT => 10
            ),
    );

}

print_r($targets);

?>

However it only seems to display the last populated value:

Array
(
[http://127.0.0.1/?page=20] => Array
    (
        [13] => 10
    )

)

I also tried changing : " $targets = " to " $targets[] = " however it produces this output :

[0] => Array
    (
        [http://127.0.0.1/?page=0] => Array
            (
                [13] => 10
            )

    )

[1] => Array
    (
        [http://127.0.0.1/?page=1] => Array
            (
                [13] => 10
            )

    )

[2] => Array
    (
        [http://127.0.0.1/?page=2] => Array
            (
                [13] => 10
            )

    )

While my desired output is :

Array
(
[http://127.0.0.1/?page=0] => Array
    (
        [13] => 10
    )

[http://127.0.0.1/?page=1] => Array
    (
        [13] => 10
    )

[http://127.0.0.1/?page=2] => Array
    (
        [13] => 10
    )

)

Probably an easy fix but I'm unable to see it. Can someone with more knowledge point me out my mistake ?

Thanks !

5

There are 5 answers

0
VijayS91 On BEST ANSWER

Try this Code :

$maxPages = 20;
$targets = array();
for ($i = 0; $i <= $maxPages; $i++) {

    $url = 'http://127.0.0.1/?page='.$i;

        $targets[$url] =  array(
            CURLOPT_TIMEOUT => 10
        );

}
echo "<pre>";
print_r($targets);
1
LeleDumbo On

As simple as changing the loop body to:

$targets[] =  array( // <-- NOTE THE []
        $url => array(
                CURLOPT_TIMEOUT => 10
        ),
);
1
Peter On
$targets[] = array(
        $url => array(
                CURLOPT_TIMEOUT => 10
        ),
);

Use [] to append the array to $targets instead of overwriting.

0
efenacigiray On
$targets = array();
for ($i = 0; $i <= $maxPages; $i++) {

  $url = 'http://127.0.0.1/?page='.$i;

  **$targets[]** =  array(
        $url => array(
                CURLOPT_TIMEOUT => 10
        ),
  );

}

use targets[] to create a new array each loop

1
Ankh On

So from what we deduced in the comments: Your first issue is that you're reassigning the $targets variable in the loop rather than appending to the array using the [] notation.

Then we discovered that you need to set the key of $targets to be $url so that's easily fixed by adding $url into the square brackets [$url]. Which gives us:

$targets[$url] = array(
    CURLOPT_TIMEOUT => 10
);