PHP 7 interview question · Most asked
What is the difference between `array_merge()` and the `+` operator on arrays?
Summary
array_merge() appends and renumbers integer keys, while string keys from later arrays overwrite earlier ones. + keeps the left array's keys and only adds keys that don't already exist.
Longer Answer
[0 => 'a'] + [0 => 'b'] gives [0 => 'a']; array_merge([0 => 'a'], [0 => 'b']) gives ['a', 'b']. + is handy for applying defaults: $options + $defaults. array_replace() overwrites by key without renumbering.
Key Points
array_merge: renumber ints, overwrite strings+: left wins, nothing renumbered$options + $defaultsfor defaultsarray_replaceoverwrites by key
More most-asked PHP 7 questions
- What are typed properties in PHP 7.4?
- How do return type declarations work in PHP 7?
- What were the headline improvements of PHP 7.0 over PHP 5.6?
- Explain scalar type declarations and coercive vs strict mode in PHP 7.
- Explain the `Throwable`, `Error` and `Exception` hierarchy introduced in PHP 7.
- What are nullable types in PHP 7.1?
- What does the null coalescing operator `??` do, and how is it different from `isset()` with a ternary?
- What are arrow functions in PHP 7.4 and how do they differ from closures?