0

I am trying to split an array into two parts.

$collection = collect( [1, 2, 15, 16] );

$groups = $collection->split( 2 );

The results are... mixed:

(2) [Array(2), {…}]
    0: Array(2)
        0: 1
        1: 2
        length: 2
        __proto__: Array(0)
    1: 
        2: 15
        3: 16
        __proto__: Object
    length: 2
    __proto__: Array(0)

I am not sure if it is a bug or I am missing something. If I split into more groups, the first one is always an array and others are objects. Why does it do that and how can I make the output type consistent?


P.S. A quick solution is to use array_chunk( $collection, 2 ) if the collections happens to be an array with numeric indexes as in the case of this example. According to the answer below, if the indexes are not numeric, then this problem should not occur.

3
  • 2
    What does __proto__ property do there? I think this result is from the javascript console Commented Nov 8, 2017 at 13:29
  • @YouneL Hmm good point. It is from console. I guess perhaps by the time it arrives to the front end something happens to it. I need to look into that Commented Nov 8, 2017 at 13:33
  • 1
    Nothing happens to anything. json_encoding array with numeric keys starting not from 0 gives you an object. Commented Nov 8, 2017 at 13:34

3 Answers 3

2

This is an obvious example:

$a = [[1,2], [2 => 2, 3 => 3]];
echo json_encode($a);

Output is:

[[1,2],{"2":2,"3":3}]

First element will be array because keys in it are zero-indexed, second will be object, because keys in it are not zero-indexed.

Sign up to request clarification or add additional context in comments.

Comments

1

Nope, you probably missing something. if you split a collection, the result will be collection of collections:

Illuminate\Support\Collection {#1178
#items: array:2 [
    0 => Illuminate\Support\Collection {#1177
      #items: array:2 [
        0 => 1
        1 => 2
      ]
    }
    1 => Illuminate\Support\Collection {#1156
      #items: array:2 [
        2 => 15
        3 => 16
      ]
    }
  ]
}

Comments

-1

You also need to call $groups->toArray() method as well.

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.