根據來自另一個數組的值更新PHP數組
使用array_merge() 可以簡單地用第二個數組的值覆蓋更新原數組;2. 使用聯合運算符( ) 能保留原數組值,僅添加缺失的鍵(適合設置默認值);3. 通過foreach 結合條件判斷可實現細粒度控制,如僅更新非空值;4. 對於嵌套數組,應使用array_replace_recursive() 實現深度更新;5. 更新時應始終用array_key_exists() 或isset() 安全檢查鍵的存在性以避免錯誤;這些方法覆蓋了PHP中基於另一數組更新數組的主要場景,並應根據數據結構和邏輯選擇合適方式,確保操作安全有效。
When working with PHP, you'll often need to update one array based on the values from another—especially when dealing with form data, database records, or configuration settings. This operation can involve merging, overwriting, or selectively updating elements. Here's how to do it effectively and safely.

1. Using array_merge()
for Simple Updates
The most straightforward way to update an array with values from another is array_merge()
. It combines arrays, with later values overwriting earlier ones for matching keys.
$original = [ 'name' => 'John', 'email' => 'john@example.com', 'age' => 30 ]; $updates = [ 'email' => 'john.doe@example.com', 'age' => 31 ]; $updated = array_merge($original, $updates); // Result: // [ // 'name' => 'John', // 'email' => 'john.doe@example.com', // 'age' => 31 // ]
Note:
array_merge()
only works reliably with string or numeric keys. If the arrays have numeric keys, values are reindexed and appended.
2. Using the Union Operator (
) to Preserve Original Values
If you want to update only missing keys (ie, default values), use the union operator. It keeps the first array's values and adds only keys not present in it.
$defaults = [ 'name' => 'Anonymous', 'status' => 'inactive', 'role' => 'user' ]; $provided = [ 'name' => 'Alice', 'status' => 'active' ]; $result = $provided $defaults; // Result: Only adds 'role' from defaults // [ // 'name' => 'Alice', // 'status' => 'active', // 'role' => 'user' // ]
This is useful for setting defaults without overwriting user input.

3. Selective Update with foreach
and Conditions
Sometimes you want more control—like updating only non-empty values or validating before update.
foreach ($updates as $key => $value) { if (array_key_exists($key, $original)) { // Only update existing keys $original[$key] = $value; } }
Or update only if the new value is not null:
foreach ($updates as $key => $value) { if ($value !== null) { $original[$key] = $value; } }
This gives you full control over the update logic.
4. Handling Nested Arrays with array_replace_recursive()
For multi-dimensional arrays, array_merge()
won't deeply merge nested structures. Use array_replace_recursive()
instead.
$config = [ 'database' => [ 'host' => 'localhost', 'port' => 3306, 'username' => 'root' ], 'debug' => true ]; $overrides = [ 'database' => [ 'host' => '192.168.1.100', 'username' => 'admin' ], 'debug' => false ]; $newConfig = array_replace_recursive($config, $overrides);
Now both host
and username
inside database
are updated, while port
remains unless overridden.
Note:
array_replace_recursive()
does not merge keys that are arrays in one but not the other in the same way—be cautious with mixed types.
5. Using array_key_exists()
or isset()
for Safety
Always check if a key exists before using it, especially when the update array comes from user input or external sources.
if (array_key_exists('email', $updates)) { $original['email'] = $updates['email']; }
Use isset()
if you want to skip null
values:
if (isset($updates['email'])) { $original['email'] = $updates['email']; }
Summary
- Use
array_merge()
to overwrite values with a second array. - Use
$updates $defaults
to fill in missing values. - Use
foreach
with conditions for fine-grained control. - Use
array_replace_recursive()
for nested arrays. - Always validate keys and values when updating from untrusted sources.
These techniques cover most real-world scenarios for updating PHP arrays based on another. Choose the method that fits your data structure and update logic.基本上就這些。
以上是根據來自另一個數組的值更新PHP數組的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undress AI Tool
免費脫衣圖片

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

使用array_merge()可以簡單地用第二個數組的值覆蓋更新原數組;2.使用聯合運算符( )能保留原數組值,僅添加缺失的鍵(適合設置默認值);3.通過foreach結合條件判斷可實現細粒度控制,如僅更新非空值;4.對於嵌套數組,應使用array_replace_recursive()實現深度更新;5.更新時應始終用array_key_exists()或isset()安全檢查鍵的存在性以避免錯誤;這些方法覆蓋了PHP中基於另一數組更新數組的主要場景,並應根據數據結構和邏輯選擇合適方式,確保操作

array_walk是PHP中用於就地修改數組元素的強大函數,適用於需基於鍵名、嵌套結構或外部狀態進行複雜轉換的場景。 1.它通過引用傳遞數組和元素,直接修改原數組;2.回調函數可訪問鍵和值,並支持第三個參數傳遞上下文;3.可結合遞歸處理多維數組;4.適合批量修改對象屬性;5.不返回新數組,性能優於array_map但不適用於需保留原數組的場景。正確使用時,它在處理上下文相關或遞歸數據轉換中表現高效且代碼簡潔。

TOOPTIMIZELARGE-SCALARAYUPDATES:1.MutatearRaysInplaceInsteadOfCrowingCopiesusIsesspreadorConcattoreCattoredUceMoryUsage; 2.BatchupDateStomInimizeFunctionCalloverhead,pre-AllocateArrayseSizeisknown,sizeIskNown,and ChunkunkunkllargeInsertionStocallStoElstoelstoelstoelstoelstoelstoionclinclimstoelstoelstoelstoelstoelstoelstoelstoelstoelstoelstoelstoelstoelstoelstoelstoelstoelstoidclim;

Userecursivefunctionstosafelytraverseandupdatenestedarrayswithunknowndepthbycreatingmissingkeysasneeded.2.Leveragearrayreferenceswiththe&operatortodirectlymodifyoriginalarrayelementswithouttriggeringcostlycopiesduringdeeptraversal.3.Implementdotn

DynamicArraysallaySallayRuntimemodification byaddingorupdatingelements,withBestPracticesSistrictersing效率和安全性。 1)usepush/appendToAddelements.2 theEndforoptimalperformance.2)避免使用nunshift/insertormiddleInsertions whenperions whenperions whenphenpersions whenpossions,astheyrequireshiftingelementsa

要實現PHP中的不可變數組更新,必須通過創建新數組而非修改原數組來完成,1.避免直接修改數組元素,應使用array_merge()或手動複製生成新數組;2.使用array_merge()進行簡潔的不可變更新,保持原數組不變並支持添加新鍵;3.對嵌套數組使用純函數如遞歸setIn()函數,確保深層結構更新時不產生副作用;4.結合array_map、array_filter等函數式工具,實現無副作用的數據處理;5.通過約定強化不可變性,如將輸入數組視為只讀、返回新數組、使用PHP8.2 的reado

ArraySofObjectsInphpContainClassInstances,允許基於directPropertyormethod的模塊化; 2.UpdatePropertiesusingforeachloopssincebopssincebopssincebopssobjectsarepassedbyByReference,oruestertersterstersforencapsualderpalpulyproperties; 3.filterobjectswitharray_filteraray_filteraray_filterterterterterterterterterterterterterterterterterterterterterteSeSetsubSetsBase

使用PHP引用可实现数组的原地更新,避免复制开销并提升性能。1.使用&操作符创建引用,使变量指向同一数据,修改即反映到原数组;2.处理嵌套数组时,通过&获取深层元素引用,直接修改而无需重新赋值;3.在foreach循环中使用&$item可修改原数组元素,但循环后必须unset($item)以防止后续副作用;4.可编写函数通过动态路径返回深层引用,适用于配置管理等场景;5.引用虽高效,但应谨慎使用,避免过度复杂化代码,确保逻辑清晰且必要时添加注释。正确使用引用能显著优化大型
