萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 獲取陣列最後一個元素的 4 種方法與刪除尾端元素實戰

方法對比速查

方法適用陣列類型副作用效能推薦度
end($arr)所有(關聯/索引/多維)移動內部指標到末尾O(1)⭐⭐⭐⭐⭐
$arr[count($arr)-1]連續數值索引 (0,1,2...)無O(1)⭐⭐⭐ (僅索引陣列)
array_pop($arr)所有刪除並返回最後元素,指標重置O(1)⭐⭐⭐⭐ (需刪除時)
array_slice($arr, -1, 1, true)所有無(返回新陣列)O(1) 近似⭐⭐⭐ (需保留鍵名)
reset($arr); while(next($arr)){}; current($arr)所有指標移至末尾O(n)⭐ (教學用)

詳細範例

1. end():最通用、最直觀

<?php
$arr = ['a' => 1, 'b' => 2, 'c' => 3];
$last = end($arr);  // 3
echo "最後值: $last, 鍵名: " . key($arr) . "\n"; // 鍵名: c

// 關聯陣列同樣適用
$assoc = ['id' => 10, 'name' => 'Bob'];
echo end($assoc); // Bob

// ⚠️ 注意:end() 會移動內部指標
// 後續 foreach 會從頭開始(foreach 會自動 reset),但 current()/key() 會受影響
?>

2. 索引陣列專用:$arr[count($arr)-1]

<?php
$indexed = [10, 20, 30, 40, 50];
$last = $indexed[count($indexed) - 1]; // 50

// ❌ 關聯陣列失效
$assoc = ['x' => 1, 'y' => 2];
// count($assoc) = 2, $assoc[1] 不存在(鍵名是 'y')
?>

3. array_pop():取出並移除

<?php
$stack = ['orange', 'banana', 'apple', 'raspberry'];
$fruit = array_pop($stack); // 'raspberry'
print_r($stack);
/* 
Array
(
    [0] => orange
    [1] => banana
    [2] => apple
)
*/

// 應用:堆疊、移除末尾垃圾資料
while (($item = array_pop($queue)) !== null) {
    process($item);
}
?>

4. array_slice():非破壞性、保留鍵名

<?php
$arr = ['a' => 1, 'b' => 2, 'c' => 3];
$last = array_slice($arr, -1, 1, true); // ['c' => 3]
$lastVal = array_pop(array_slice($arr, -1, 1, true)); // 3 (但較繁瑣)

// 取最後 N 個
$last3 = array_slice($arr, -3, 3, true); // 保留鍵名
?>

多維陣列:取得最後一行/最後一欄

<?php
$matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
];

// 最後一行
$lastRow = end($matrix); // [7,8,9]

// 最後一欄(需遍歷)
$lastCol = array_column($matrix, 2); // [3, 6, 9] (PHP 5.5+)
// 或
$lastCol = array_map(function($row) { return end($row); }, $matrix);
?>

刪除最後一個元素

<?php
// 1. array_pop() - 返回被刪除的值
$val = array_pop($arr);

// 2. unset() 保留鍵名(需知鍵名)
$lastKey = key(array_slice($arr, -1, 1, true));
unset($arr[$lastKey]);

// 3. array_splice() - 就地修改,返回被刪除陣列
array_splice($arr, -1); // 刪除最後一個
?>

效能微基準測試(百萬次循環)

<?php
$arr = range(1, 100);
$iterations = 1_000_000;

$start = microtime(true);
for ($i = 0; $i < $iterations; $i++) { $x = end($arr); }
echo "end(): " . (microtime(true) - $start) . "s\n";

$start = microtime(true);
for ($i = 0; $i < $iterations; $i++) { $x = $arr[count($arr)-1]; }
echo "index: " . (microtime(true) - $start) . "s\n";

$start = microtime(true);
for ($i = 0; $i < $iterations; $i++) { $x = array_slice($arr, -1, 1, true); }
echo "slice: " . (microtime(true) - $start) . "s\n";

/* 典型輸出(PHP 8.1, JIT 開啟):
end(): 0.08s
index: 0.06s
slice: 0.45s
*/
?>

總結建議

  • 🎯 只需讀取值:end($arr)(通用)、$arr[count($arr)-1](純索引陣列、極致效能)
  • 🗑️ 需讀取並移除:array_pop($arr)
  • 🔒 需保留原陣列、保留鍵名:array_slice($arr, -1, 1, true)
  • ⚡ 高頻熱點路徑:索引陣列用下標存取最快,關聯陣列用 end()
  • 🧪 測試代碼:用 end() 後記得 reset($arr) 或用 foreach(自動 reset)避免指標副作用
copyright © 萬盛學電腦網 all rights reserved