Interview question
What is the difference between array_merge() and the + operator for combining arrays? array_merge() और arrays जोड़ने के लिए + operator में क्या अंतर है?
Answer
Both combine two arrays, but they handle duplicate keys very differently.
| Aspect | array_merge() | + operator |
|---|---|---|
| String keys, duplicate | Later array's value overwrites earlier | Earlier (left) array's value wins |
| Integer keys | Re-indexed sequentially | Original integer keys preserved |
$a = ['name' => 'Raj', 0 => 'x'];
$b = ['name' => 'Amit', 0 => 'y'];
print_r(array_merge($a, $b));
// ['name' => 'Amit', 0 => 'x', 1 => 'y'] -- b overwrites, ints re-indexed
print_r($a + $b);
// ['name' => 'Raj', 0 => 'x'] -- a wins, int keys preservedInterview tip: This is a classic trick question because the results are opposite for string keys - always test with a concrete example when explaining, don't just state the rule.
दोनों दो arrays जोड़ते हैं, पर duplicate keys को बहुत अलग तरीके से handle करते हैं।
| पहलू | array_merge() | + operator |
|---|---|---|
| String keys, duplicate | बाद वाले array की वैल्यू पहले वाले को overwrite करती है | पहले (left) array की वैल्यू जीतती है |
| Integer keys | क्रमवार re-index होते हैं | Original integer keys बने रहते हैं |
$a = ['name' => 'Raj', 0 => 'x'];
$b = ['name' => 'Amit', 0 => 'y'];
print_r(array_merge($a, $b));
// ['name' => 'Amit', 0 => 'x', 1 => 'y'] -- b overwrite करता है, ints re-indexed
print_r($a + $b);
// ['name' => 'Raj', 0 => 'x'] -- a जीतता है, int keys preservedइंटरव्यू टिप: यह एक क्लासिक ट्रिक सवाल है क्योंकि string keys के लिए results उलटे हैं - समझाते समय हमेशा concrete उदाहरण से टेस्ट करें, सिर्फ नियम मत बताएं।
Was this answer clear?