$keys = ['green', 'red', 'yellow'];
$values = ['avocado', 'apple', 'banana'];
$combined = array_combine($keys, $values);
// ['green'=>'avocado', 'red'=>'apple', 'yellow'=>'banana']
兩陣列長度必須相等,否則回傳 false 並觸發警告。
$a = ['color' => 'red', 2, 4];
$b = ['a', 'b', 'color' => 'green', 'shape' => 'trapezoid', 4];
$merged = array_merge($a, $b);
/*
[
'color' => 'green', // 字串鍵覆蓋
0 => 2, // 數字鍵 0
1 => 4, // 數字鍵 1
2 => 'a', // 重新索引 0->2
3 => 'b', // 重新索引 1->3
'shape' => 'trapezoid',
4 => 4 // 重新索引
]
*/
$ar1 = ['color' => ['favorite' => 'red'], 5];
$ar2 = [10, 'color' => ['favorite' => 'green', 'blue']];
$merged = array_merge_recursive($ar1, $ar2);
/*
[
'color' => ['favorite' => ['red', 'green'], 0 => 'blue'],
0 => 5,
1 => 10
]
*/
$input = ['a', 'b', 'c', 'd', 'e'];
array_slice($input, 2); // ['c','d','e'] 從索引 2 到結尾
array_slice($input, -2, 1); // ['d'] 倒數第 2 取 1 個
array_slice($input, 0, 3); // ['a','b','c'] 從頭取 3 個
array_slice($input, 2, -1); // ['c','d'] 從索引 2 到倒數第 1 (不含)
array_slice($input, 2, -1, true); // 保留鍵 ['2'=>'c','3'=>'d']
$input = ['red', 'green', 'blue', 'yellow'];
array_splice($input, 2); // 移除索引 2 之後 => ['red','green']
array_splice($input, 1, -1); // 移除索引 1 到倒數第 1 => ['red','yellow']
array_splice($input, 1, count($input), 'orange'); // 索引 1 開始全換 => ['red','orange']
array_splice($input, -1, 1, ['black','maroon']); // 最後一個換成兩個
array_splice($input, 3, 0, 'purple'); // 索引 3 插入 (不移除)
$a = ['a'=>'green', 'red', 'blue'];
$b = ['b'=>'green', 'yellow', 'red'];
array_intersect($a, $b); // ['a'=>'green', 0=>'red']
$a = ['a'=>'green', 'b'=>'brown', 'c'=>'blue', 'red'];
$b = ['a'=>'green', 'yellow', 'red'];
array_intersect_assoc($a, $b); // ['a'=>'green']
$a = ['a'=>'green', 'red', 'blue', 'red'];
$b = ['b'=>'green', 'yellow', 'red'];
array_diff($a, $b); // [1=>'blue'] (數字鍵 1 保留)
$a = ['a'=>'green', 'b'=>'brown', 'c'=>'blue', 'red'];
$b = ['a'=>'green', 'yellow', 'red'];
array_diff_assoc($a, $b); // ['b'=>'brown', 'c'=>'blue', 0=>'red']
| 需求 | 推薦函數 | 注意 |
|---|---|---|
| 兩陣列鍵值配對 | array_combine | 長度必須相等 |
| 簡單合併,數字鍵重新索引 | array_merge | 字串鍵後覆蓋前 |
| 合併保留相同鍵所有值 | array_merge_recursive | 值變陣列 |
| 取出子陣列不修改原陣列 | array_slice | 第四參數 true 保留鍵 |
| 移除/替換/插入修改原陣列 | array_splice | 回傳被移除部分 |
| 找共同值 | array_intersect | 只比值 |
| 找共同鍵值對 | array_intersect_assoc | 鍵值都要同 |
| 找差異值 | array_diff | 只比值 |
| 找差異鍵值對 | array_diff_assoc | 鍵值都要同 |