目錄
1. Avoid Modifying Arrays In Place
2. Use array_merge() for Clean Immutable Updates
3. Handle Nested Updates with Pure Functions
4. Combine with Functional Helpers
5. Embrace Immutability by Convention
首頁 後端開發 php教程 使用功能性php的不變陣列更新的藝術

使用功能性php的不變陣列更新的藝術

Aug 05, 2025 pm 12:30 PM
PHP Update Array Items

要實現PHP中的不可變數組更新,必須通過創建新數組而非修改原數組來完成,1. 避免直接修改數組元素,應使用array_merge()或手動複製生成新數組;2. 使用array_merge()進行簡潔的不可變更新,保持原數組不變並支持添加新鍵;3. 對嵌套數組使用純函數如遞歸setIn()函數,確保深層結構更新時不產生副作用;4. 結合array_map、array_filter等函數式工具,實現無副作用的數據處理;5. 通過約定強化不可變性,如將輸入數組視為只讀、返回新數組、使用PHP 8.2 的readonly類或DTO封裝數據。這種方法提升了代碼的可預測性、可維護性和可測試性,最終實現更安全的狀態管理。

The Art of Immutable Array Updates Using Functional PHP

Immutable array updates in PHP might sound like a concept borrowed from functional programming languages like Haskell or Elm, but you can apply the same principles effectively even in PHP—especially as the language matures with features supporting functional patterns.

The Art of Immutable Array Updates Using Functional PHP

The core idea is simple: instead of modifying an array in place, you create a new array that includes the desired changes, leaving the original untouched. This leads to more predictable code, easier debugging, and fewer side effects—especially valuable in larger applications or when working with state in a functional style.

Here's how to master immutable array updates in PHP using functional techniques.

The Art of Immutable Array Updates Using Functional PHP

1. Avoid Modifying Arrays In Place

In traditional PHP, you might do something like:

 $user = ['name' => 'Alice', 'age' => 30];
$user['age'] = 31; // Mutation!

This mutates the original array. Instead, create a new version:

The Art of Immutable Array Updates Using Functional PHP
 $user = ['name' => 'Alice', 'age' => 30];
$newUser = ['name' => $user['name'], 'age' => $user['age'] 1];

Now $user remains unchanged, and $newUser reflects the update.

But manually copying keys gets tedious. Use the spread-like behavior of or array_merge() .


2. Use array_merge() for Clean Immutable Updates

array_merge() is your go-to tool for creating updated copies:

 $user = ['name' => 'Alice', 'age' => 30];
$updatedUser = array_merge($user, ['age' => 31]);

This returns a new array. The original $user is untouched.

You can also add new keys:

 $extendedUser = array_merge($user, ['active' => true]);

Important: array_merge() only works reliably with indexed or associative arrays, not complex nested structures unless handled recursively.


3. Handle Nested Updates with Pure Functions

For nested arrays, immutability requires deeper care. Don't do this:

 $data['user']['profile']['theme'] = 'dark'; // Mutation!

Instead, build a pure function to return a new structure:

 function withUpdatedTheme(array $data, string $theme): array
{
    return array_merge($data, [
        'user' => array_merge($data['user'], [
            'profile' => array_merge($data['user']['profile'], [
                'theme' => $theme
            ])
        ])
    ]);
}

Usage:

 $newData = withUpdatedTheme($data, 'dark');

Now $data is preserved, and changes are encapsulated in a reusable, testable function.

For deeply nested data, consider writing a generic setIn() function:

 function setIn(array $array, array $path, $value): array
{
    $result = $array;
    $cursor = &$result;

    foreach ($path as $key) {
        if (!is_array($cursor)) {
            $cursor = [];
        }
        $cursor = &$cursor[$key];
    }

    $cursor = $value;

    return $result;
}

Wait—this uses references and mutates $result . Not pure.

Here's a truly immutable version:

 function setIn(array $array, array $path, $value): array
{
    if (empty($path)) {
        return $array;
    }

    $key = array_shift($path);
    if (!empty($path)) {
        $nested = $array[$key] ?? [];
        if (!is_array($nested)) {
            $nested = [];
        }
        $array[$key] = setIn($nested, $path, $value);
    } else {
        $array[$key] = $value;
    }

    return $array;
}

Now you can do:

 $newData = setIn($data, ['user', 'profile', 'theme'], 'dark');

And $data remains unchanged.


4. Combine with Functional Helpers

To make this style more expressive, pair immutable updates with functional helpers.

For example, map over arrays without mutation:

 $users = [['name' => 'Alice', 'age' => 30], ['name' => 'Bob', 'age' => 25]];

$usersAgedUp = array_map(
    fn($user) => array_merge($user, ['age' => $user['age'] 1]),
    $users
);

Or filter:

 $activeUsers = array_filter($users, fn($user) => $user['active'] ?? false);

These don't alter the original $users array—pure and predictable.


5. Embrace Immutability by Convention

PHP doesn't enforce immutability, so discipline matters. Tips:

  • Treat arrays passed into functions as read-only.
  • Return new arrays instead of modifying inputs.
  • Use readonly classes (PHP 8.2 ) when modeling data structures.
  • Consider using value objects or DTOs for complex data.

Example with a readonly class:

 readonly class User
{
    public function __construct(
        public string $name,
        public int $age
    ) {}
}

function withAgeIncreased(User $user, int $by = 1): User
{
    return new User($user->name, $user->age $by);
}

Now immutability is enforced at the object level.


Immutable array updates in PHP aren't automatic, but with array_merge() , pure functions, and functional thinking, you can write safer, more maintainable code. It's not about copying everything—it's about control, clarity, and avoiding unintended consequences.

Basically, if you treat data as if it can't be changed, you'll write better PHP.

以上是使用功能性php的不變陣列更新的藝術的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

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

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

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

熱門話題

PHP教程
1596
276
用於更新多維PHP陣列的高級技術 用於更新多維PHP陣列的高級技術 Aug 03, 2025 am 06:26 AM

Userecursivefunctionstosafelytraverseandupdatenestedarrayswithunknowndepthbycreatingmissingkeysasneeded.2.Leveragearrayreferenceswiththe&operatortodirectlymodifyoriginalarrayelementswithouttriggeringcostlycopiesduringdeeptraversal.3.Implementdotn

根據來自另一個數組的值更新PHP數組 根據來自另一個數組的值更新PHP數組 Aug 02, 2025 am 12:51 AM

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

深入研究' array_walk”,以進行複雜的數組變換 深入研究' array_walk”,以進行複雜的數組變換 Aug 02, 2025 pm 03:28 PM

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

動態陣列修改:即時添加或更新元素 動態陣列修改:即時添加或更新元素 Aug 02, 2025 pm 03:37 PM

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

優化大型數組更新操作以進行內存和速度 優化大型數組更新操作以進行內存和速度 Aug 02, 2025 am 02:08 AM

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

使用功能性php的不變陣列更新的藝術 使用功能性php的不變陣列更新的藝術 Aug 05, 2025 pm 12:30 PM

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

使用PHP參考來掌握現場陣列更新 使用PHP參考來掌握現場陣列更新 Aug 05, 2025 pm 04:46 PM

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

修改PHP中對象陣列的指南 修改PHP中對象陣列的指南 Aug 04, 2025 am 12:38 AM

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

See all articles