0

I have an array like this in php

Array
(
    [0] => 1
    [1] => 3
    [2] => 5
    [3] => 10
    [4] => 14
    [5] => 15
)

Now I want it to look like

Array
(
    [0] => Array
        (
           [0] => 1
           [1] => 3
        )
    [1] => => Array
        (
           [0] => 5
           [1] => 10
        )
    [2] => => Array
        (
           [0] => 14
           [1] => 15
        )
)

Please suggest how to get the desired output using for loop.

2
  • Why use a for loop? Why not simply use array_chunk()? php.net/manual/en/function.array-chunk.php Commented Mar 26, 2013 at 13:55
  • Thanks Mark for the inbuilt function.Actually I like for loop with nested array which is really interesting(sometimes). Commented Mar 26, 2013 at 14:03

3 Answers 3

4

You could try something like this

$length = count($array);
$newArray = array();
for ($i = 0; $i < $length; $i +=2){
   $newArray[] = array($array[$i], $array[$i + 1])
}
Sign up to request clarification or add additional context in comments.

3 Comments

A minor note but I believe caching the value of count($array) to $length doesn't do much here. It's a different case when you have something like $i < $list->length because then every time the interpreter will have to find $list and look at it's property $length. Something to keep in mind ;)
Thanks a lot Adnan.It's a great help.
@FritsvanCampen Thank you for your politeness, but I think I'll disagree with you on that one. Check out this test codepad.org/oVFpsRdI
3
for($i = 0, $count = count($array1); $i < $count; $i = $i + 2) {
    $array2[] = array($array1[$i], $array1[$i+1]);
}

print_r($array2);

1 Comment

One word 'brilliant'...thanks Michael for your help.The trick is in the for loop ($i = $ + 2)).I missed this part....Thanks.
2

Something that looks like :

for ($i = 0 ; $i < count($arr) ; $i += 2) {
    ...
}

Note that I increment $i twice on each iteration as I'm working with pairs of items : int the loop, I'll use $arr[$i] and $arr[$i+1] on each iteration. Note that this will not work correctly is the n# of items is not even !

The rest should be rather straightforward.

1 Comment

Thanks a bunch Fab.It was driving me nuts..:)

Your Answer

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