PHP อาร์เรย์ — list และ associative



ใน PHP “อาร์เรย์” เป็นโครงสร้างเดียวที่ทำหน้าที่ทั้ง list, dictionary/map, และ stack/queue — จริง ๆ มันคือ ordered map ที่ยืดหยุ่นมาก

อาร์เรย์แบบ list

index เป็นตัวเลขเริ่มจาก 0 อัตโนมัติ:

<?php
declare(strict_types=1);

$fruits = ['แอปเปิล', 'กล้วย', 'ส้ม'];

echo $fruits[0], "\n";        // แอปเปิล
echo $fruits[2], "\n";        // ส้ม
echo count($fruits), "\n";    // 3

$fruits[] = 'องุ่น';          // เพิ่มต่อท้าย
echo $fruits[3], "\n";        // องุ่น

อาร์เรย์แบบ associative

key เป็นสตริงที่เราตั้งเอง — เหมาะกับข้อมูลที่มีชื่อฟิลด์:

<?php
$user = [
    'name'  => 'สมชาย',
    'age'   => 30,
    'email' => 'somchai@example.com',
];

echo $user['name'], "\n";        // สมชาย
$user['age'] = 31;               // แก้ค่า
$user['phone'] = '0812345678';   // เพิ่ม key ใหม่

print_r($user);
Array
(
    [name] => สมชาย
    [age] => 31
    [email] => somchai@example.com
    [phone] => 0812345678
)

เข้าถึง key ที่อาจไม่มี

<?php
$config = ['debug' => true];

// echo $config['timeout'];          // Warning: Undefined array key
echo $config['timeout'] ?? 30, "\n"; // 30 — ใช้ ?? เสมอ

var_dump(isset($config['debug']));           // true
var_dump(array_key_exists('debug', $config)); // true

ความต่าง: isset() คืน false ถ้า key มีอยู่แต่ค่าเป็น null ส่วน array_key_exists() สนใจแค่ว่ามี key ไหม (บทที่ 14 จะเจาะเรื่องนี้)

ลบสมาชิก

<?php
$nums = [10, 20, 30, 40];
unset($nums[1]);

print_r($nums);
// [0 => 10, 2 => 30, 3 => 40]   — สังเกตว่า index 1 หายไป ไม่มีการเรียงใหม่!

ถ้าอยากได้ index เรียงต่อกันใหม่ (0, 1, 2…) ใช้ array_values():

<?php
$nums = array_values($nums);
print_r($nums);              // [0 => 10, 1 => 30, 2 => 40]

นี่เป็นกับดักใหญ่: หลัง unset() หรือ array_filter() อาร์เรย์อาจมี index กระโดด ทำให้ $nums[1] ไม่ใช่สมาชิกตัวที่สองเสมอไป และ json_encode() จะได้ object แทน array

อาร์เรย์ซ้อน

<?php
$students = [
    ['name' => 'อร', 'scores' => [80, 75, 90]],
    ['name' => 'บอย', 'scores' => [60, 85, 70]],
];

echo $students[0]['name'], "\n";           // อร
echo $students[1]['scores'][2], "\n";      // 70

foreach ($students as $s) {
    $avg = array_sum($s['scores']) / count($s['scores']);
    echo "{$s['name']}: เฉลี่ย " . round($avg, 1) . "\n";
}
อร: เฉลี่ย 81.7
บอย: เฉลี่ย 71.7

destructuring ด้วย [ ]

แตกอาร์เรย์ออกเป็นตัวแปร:

<?php
[$a, $b, $c] = [1, 2, 3];
echo "$a $b $c\n";           // 1 2 3

// ข้ามบางตัว
[, , $third] = ['x', 'y', 'z'];
echo $third, "\n";           // z

// จาก associative — ระบุ key
['name' => $name, 'age' => $age] = ['name' => 'อร', 'age' => 25];
echo "$name อายุ $age\n";

// ใช้ใน foreach
$points = [[1, 2], [3, 4], [5, 6]];
foreach ($points as [$x, $y]) {
    echo "($x, $y) ";
}
echo "\n";

spread operator …

รวมอาร์เรย์:

<?php
$a = [1, 2, 3];
$b = [4, 5, 6];
$all = [...$a, ...$b, 7];        // [1, 2, 3, 4, 5, 6, 7]

// รวม associative (key ซ้ำ ตัวหลังชนะ) — PHP 8.1+
$defaults = ['color' => 'ขาว', 'size' => 'M'];
$custom = ['size' => 'L'];
$merged = [...$defaults, ...$custom];   // ['color' => 'ขาว', 'size' => 'L']

อีกวิธีรวม associative คือ array_merge($defaults, $custom) หรือตัวดำเนินการ + (แต่ + ให้ key ซ้ายชนะ — น่าสับสน)

ฟังก์ชันอาร์เรย์ที่ใช้บ่อยที่สุด

<?php
$nums = [3, 1, 4, 1, 5, 9];

count($nums);              // 6
in_array(4, $nums, true);  // true  (พารามิเตอร์ที่ 3 = strict, ใส่เสมอ)
array_search(4, $nums, true); // 2  (คืน index หรือ false)
array_sum($nums);          // 23
max($nums); min($nums);    // 9, 1
array_unique($nums);       // [3, 1, 4, 5, 9]  (index เดิม)
array_reverse($nums);      // [9, 5, 1, 4, 1, 3]
implode(', ', $nums);      // "3, 1, 4, 1, 5, 9"

บทหน้าจะลงลึก array_map / array_filter / array_reduce / การเรียงลำดับ

เรื่องที่คนมักพลาด

  • คิดว่า unset($arr[1]) จะเลื่อน index มันไม่เลื่อน — ต้อง array_values() ถ้าต้องการ index ต่อเนื่อง
  • in_array($x, $arr) ไม่ใส่ strict — in_array(0, ['a', 'b']) เป็น true ใน PHP 7 (loose) ใส่ true เป็นพารามิเตอร์ที่ 3 เสมอ
  • $arr['key'] โดยตรงทั้งที่ key อาจไม่มี ทำให้เกิด warning ใช้ ?? ค่าเริ่มต้น
  • array_merge กับอาร์เรย์ที่ key เป็นตัวเลข จะ re-index (0,1,2…) ไม่รักษา key เดิม — ถ้าต้องรักษา key ใช้ + หรือ spread
  • json_encode() อาร์เรย์ที่ index ไม่เริ่มจาก 0 หรือกระโดด จะได้ JSON object {"0":...,"2":...} ไม่ใช่ array — array_values() ก่อน encode
  • เทียบอาร์เรย์ด้วย == vs === — == เท่ากันเมื่อ key/value เหมือนกัน (ไม่สนลำดับ), === ต้องลำดับเดียวกันด้วย

สรุป

  • อาร์เรย์ PHP เป็น ordered map — เป็นได้ทั้ง list (index ตัวเลข) และ associative (key สตริง)
  • เข้าถึง key ที่อาจไม่มีด้วย $arr['k'] ?? default
  • unset() ไม่ re-index — ใช้ array_values() เมื่อจำเป็น
  • destructure ด้วย [$a, $b] = ... และ ['k' => $v] = ..., รวมอาร์เรย์ด้วย ... spread
  • ใส่ true (strict) ให้ in_array() / array_search() เสมอ

บทถัดไปว่าด้วยฟังก์ชันจัดการอาร์เรย์ตัวหลัก — array_map, array_filter, array_reduce, และการเรียงลำดับด้วย usort