2

I have an array:

$a = array('color' => 'green', 'format' => 'text', 'link_url');

and another:

$b = array('zero', 'one', 'two', 'three', 'test' => 'ok', 'four');

And with array_merge() I have an array like this:

Array
(
    [color] => green
    [format] => text
    [0] => link_url
    [1] => zero
    [2] => one
    [3] => two
    [4] => three
    [test] => ok
    [5] => four
)

Why PHP sets array key as above? Why not like this:

Array
(
    [color] => green
    [format] => text
    [2] => link_url
    [3] => zero
    [4] => one
    [5] => two
    [6] => three
    [test] => ok
    [8] => four
)

5 Answers 5

3

That's because numeric IDs are counted separately from seeing indices. The string indices have no number and are not counted.

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

Comments

1

Quoting from the PHP manual for your original array definitions:

The key is optional. If it is not specified, PHP will use the increment of the largest previously used integer key.

and from the docs on array_merge():

If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.

Values in the input array with numeric keys will be renumbered with incrementing keys starting from zero in the result array.

So it's all quite explicitly documented

Comments

0

Well, if you look at the original array, should be clear:

array(3) {
  ["color"]=>
  string(5) "green"
  ["format"]=>
  string(4) "text"
  [0]=>
  string(8) "link_url"
}

1 Comment

0

You appear to have assumed an ordering or a congruity with non-numeric keys, which does not exist.

The numeric keys have an order and this is represented in their new values; the string keys are not part of that ordering system and thus do not affect those new numeric values.

This is simply the way it is and it makes complete sense.

Comments

0

Please check the doc :

If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.

Values in the input array with numeric keys will be renumbered with incrementing keys starting from zero in the result array.

Ref: http://www.php.net/manual/en/function.array-merge.php

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.