Search code examples
phparraysfor-looppopulation

Filling PHP array with "for" loop


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 !


Solution

  • 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);