array_values() 是 PHP 陣列操作的基石函數之一,單一職責:返回陣列中所有值,並重新建立從 0 開始的連續數字索引。它不改變原陣列,而是返回一個新陣列。
array array_values ( array $input )
$input:輸入陣列 (關聯陣列、數字索引陣列、多維陣列皆可)0, 1, 2, ...$input = [
"php" => "php code",
"html" => "html code",
"css" => "css code",
"js" => "js code"
];
$output = array_values($input);
/* 結果:
Array
(
[0] => php code
[1] => html code
[2] => css code
[3] => js code
)
原鍵名 "php", "html", "css", "js" 全部丟棄,重新編號 0-3
*/
// 資料庫查詢返回關聯陣列
$users = [
['id' => 1, 'name' => 'Alice'],
['id' => 2, 'name' => 'Bob']
];
// 前端框架 (Vue/React) 遍歷需數字索引
$userList = array_values($users);
// 現在可以安全用 $userList[0], $userList[1] 訪問
$items = ['a', 'b', 'c', 'd', 'e']; unset($items[2]); // 刪除 'c' // $items 變成 [0=>'a', 1=>'b', 3=>'d', 4=>'e'] 索引斷層 $items = array_values($items); // 重建為 [0=>'a', 1=>'b', 2=>'d', 3=>'e'] ✅
$records = [
['id' => 1, 'name' => 'A', 'score' => 90],
['id' => 2, 'name' => 'B', 'score' => 85],
['id' => 3, 'name' => 'C', 'score' => 95]
];
// 提取所有分數 (配合 array_column PHP 5.5+ 更優雅)
$scores = array_column($records, 'score'); // [90, 85, 95] 已是數字索引
// PHP 5.4 或不支援 array_column 時
$scores = array_values(array_map(function($r) { return $r['score']; }, $records));
$data = ['name' => 'John', 'age' => 30];
echo json_encode($data); // {"name":"John","age":30} → 物件 {}
$data = array_values($data);
echo json_encode($data); // ["John",30] → 陣列 [] ✅
$numbers = [10, 20, 30, 40, 50]; $filtered = array_filter($numbers, fn($n) => $n > 25); // 結果:[2=>30, 3=>40, 4=>50] 保留原索引 $reindexed = array_values($filtered); // 重建:[0=>30, 1=>40, 2=>50] ✅
function array_values_recursive($array) {
$result = [];
foreach ($array as $value) {
$result[] = is_array($value) ? array_values_recursive($value) : $value;
}
return $result;
}
$nested = [
'a' => [1, 2, 'x' => 3],
'b' => ['y' => [4, 5]]
];
print_r(array_values_recursive($nested));
/* 輸出:
Array
(
[0] => Array ( [0] => 1, [1] => 2, [2] => 3 )
[1] => Array ( [0] => Array ( [0] => 4, [1] => 5 ) )
)
*/
| 函數 | 功能 | 保留鍵名 | 重建索引 | 適用場景 |
|---|---|---|---|---|
| array_values | 提取所有值 | ❌ | ✅ 0,1,2... | 關聯轉索引、過濾後重建、JSON標準化 |
| array_keys | 提取所有鍵 | N/A | ✅ 0,1,2... | 獲取欄位名、檢查鍵是否存在 |
| array_flip | 交換鍵值 | 值變鍵 | 視值而定 | 鍵值對調、快速查找值是否存在 |
| array_combine | 合併鍵值陣列 | 第一參數作鍵 | 否 | 兩陣列合併為關聯陣列 |
| array_merge | 合併陣列 | 字串鍵覆蓋 數字鍵重建 | 部分 | 合併多個陣列、追加元素 |
$data = [['id'=>1], ['id'=>2]]; array_values($data); // 返回原陣列,因為值本身就是陣列 // 需用 array_column($data, 'id') 或 array_map
// 推薦寫法:語義清晰、單向數據流
$result = array_values(
array_filter(
array_map('trim', $rawInput),
fn($v) => $v !== ''
)
);
// 而非分步賦值 (變量汙染、難以追蹤)
$step1 = array_map('trim', $rawInput);
$step2 = array_filter($step1, ...);
$result = array_values($step2);
array_values() 是 PHP 陣列工具箱中的「索引重建器」。核心價值在於:拋棄原有鍵名,建立標準 0-based 數字索引。它是連接關聯陣列世界與數字索引世界的橋樑,廣泛應用於:資料庫結果集轉換、陣列過濾後處理、JSON 輸出標準化、前端框架數據適配。記住:不修改原陣列、返回新陣列、遞迴需自行實現。