Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Question 5 of 10 · Arrays & String Functions
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.

Aspectarray_merge()+ operator
String keys, duplicateLater array's value overwrites earlierEarlier (left) array's value wins
Integer keysRe-indexed sequentiallyOriginal 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 preserved

Interview 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?