1

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

3 Answers 3

3

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

4 Comments

output will start from array index 1
Thanks, hadn't noticed.
Why would you over-complicate such a simple thing, like $pagination[] = array('id' => $i, 'value' => $i+5);?
It just came up on top of my head, no particular reason, your answer is better and shorter.
3

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.

Comments

2

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

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.