萬盛學電腦網

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

PHP 陣列核心操作實戰:搜尋、計數、增刪、合併、排序完全指南

搜尋與計數

<?php
$names = ['Joe', 'Jane', 'Bob', 'Mary', 'Paul', 'Eddie', 'John'];

// in_array:檢查值是否存在(嚴格模式建議開啟第 3 參數 true)
$find = 'Albert';
if (in_array($find, $names, true)) {
    echo "找到 $find";
} else {
    echo "未找到 $find"; // 輸出:未找到 Albert
}

// count:元素個數
echo count($names); // 7
?>

陣列增刪操作

尾部推入/彈出

<?php
$fruits = ['apple', 'orange', 'banana', 'kiwi', 'pear'];

// 推入多個
array_push($fruits, 'grape', 'pineapple', 'tomato');
// 等同於:$fruits[] = 'grape'; $fruits[] = 'pineapple'; ...

// 彈出最後一個
$last = array_pop($fruits); // tomato
print_r($fruits);
?>

頭部推入/移出

<?php
$fruits = ['apple', 'orange', 'banana', 'kiwi', 'pear'];

// 頭部推入(索引重排)
array_unshift($fruits, 'grape', 'pineapple', 'tomato');
// 結果:grape, pineapple, tomato, apple, orange, ...

// 移出第一個
$first = array_shift($fruits); // grape
print_r($fruits);
?>

陣列合併

<?php
$fruits = ['apple', 'orange', 'banana', 'kiwi', 'pear'];
$veggies = ['carrot', 'green beans', 'asparagus', 'artichoke', 'corn'];

// 合併:數字索引重排,字串鍵後者覆蓋前者
$food = array_merge($fruits, $veggies);
print_r($food);
/*
Array (
    [0] => apple
    [1] => orange
    ...
    [5] => carrot
    [6] => green beans
    ...
)
*/
?>

排序函數家族

<?php
$fruits = ['apple', 'orange', 'banana', 'kiwi', 'pear'];

// 升序排序(值),重建索引
sort($fruits);
// 結果:apple, banana, kiwi, orange, pear

// 關聯陣列按值排序(保留鍵)
$prices = ['apple' => 50, 'banana' => 20, 'orange' => 30];
asort($prices);  // banana(20), orange(30), apple(50)
arsort($prices); // 降序

// 關聯陣列按鍵排序
ksort($prices);  // apple, banana, orange
krsort($prices); // 降序

// 自然排序(人類直覺:img2 < img10)
$files = ['img1.png', 'img10.png', 'img2.png'];
natsort($files); // img1, img2, img10
?>

實用技巧總結

  • array_push($arr, ...$items) PHP 7.3+ 支援展開運算子一次推入多個
  • [] = $val 比 array_push() 更快(單元素)
  • 大量資料用 SplFixedArray 或 Generator 節省記憶體
  • 排序前先 $arr = array_values($arr) 重建索引避免洞
  • 多維陣列排序用 array_multisort() 或 usort() 配合比較函數
copyright © 萬盛學電腦網 all rights reserved