Dibish
Dibish

Reputation: 9293

PHP Build an associative array from for-loop

I have a requirement to generate following associative array from a for-loop .

Array ( [0] => 
    Array ( 
            [id] => 1 
            [value] => 6

        ) [1] => 
        Array ( 
                [id] => 2 
                [value] => 7 

        ) [2] => 
        Array ( 
                [id] => 3 
                [value] => 8 

        ) 
    )

Tried this code

 $total_pages = 3;
 $pagination = array();
 for ($i=1; $i<=$total_pages; $i++) {
                $pagination[]['id'] = $i;
                $pagination[]['value'] = $i + 5;
            };

I have tried this code but cannot able to generate an associative array. Not sure about how to do it. Please help me to solve this issue. Thank you

Upvotes: 1

Views: 125

Answers (3)

Tibor B.
Tibor B.

Reputation: 1690

I think this is the easiest option:

$total_pages = 3;
$pagination = array();
for ($i=1; $i<=$total_pages; $i++) {
  $pagination[] = array('id' => $i, 'value' => $i+5);
};

... and also the shortest, if I check other answers.

Upvotes: 3

Ende Neu
Ende Neu

Reputation: 15783

You are generating a sub array on each iteration if you leave the [], if you provide an index instead it will work:

$total_pages = 3;
$pagination = array();
for ($i=1; $i<=$total_pages; $i++) {
  $pagination[$i - 1]['id'] = $i;
  $pagination[$i - 1]['value'] = $i + 5;
};

Upvotes: 3

Satish Sharma
Satish Sharma

Reputation: 9635

try this

$total_pages = 3;
 $pagination = array();
 for ($i=1; $i<=$total_pages; $i++) {
    $arr_temp = array();
    $arr_temp['id'] = $i;
    $arr_temp['value'] = $i + 5;
    $pagination[] = $arr_temp;
};
print_r($pagination);

OUTPUT :

Array
(
    [0] => Array
        (
            [id] => 1
            [value] => 6
        )

    [1] => Array
        (
            [id] => 2
            [value] => 7
        )

    [2] => Array
        (
            [id] => 3
            [value] => 8
        )

)

Wording Demo

Upvotes: 2

Related Questions