Skip to content
เข้าสู่ระบบ

Arrays


Arrays เป็นโครงสร้างข้อมูลที่สำคัญที่สุดใน PHP ใช้เก็บหลายค่าในตัวแปรเดียว ในบทนี้เราจะเรียนรู้การสร้างและจัดการ arrays ใน PHP 8.4+


<?php
// Short syntax (แนะนำ)
$fruits = ["apple", "banana", "orange"];
// array() syntax (เก่า)
$colors = array("red", "green", "blue");
// Empty array
$items = [];
// Numeric indices (0, 1, 2, ...)
$numbers = [10, 20, 30, 40, 50];
echo $numbers[0]; // 10
echo $numbers[2]; // 30
// กำหนด index เอง
$custom = [
0 => "zero",
5 => "five",
10 => "ten"
];
// ประกาศพร้อม type ใน PHP 8+ docblock
/** @var array<int, string> */
$stringArray = ["a", "b", "c"];

Arrays ที่ใช้ตัวเลขเป็น key:

<?php
$fruits = ["apple", "banana", "orange", "mango"];
// เข้าถึงด้วย index
echo $fruits[0]; // "apple"
echo $fruits[3]; // "mango"
// เปลี่ยนค่า
$fruits[1] = "blueberry";
// เพิ่มค่าท้ายสุด
$fruits[] = "grape"; // index 4
// เพิ่มด้วย array_push
array_push($fruits, "kiwi", "pear");
// นับจำนวน
echo count($fruits); // 7
// ตรวจสอบ index
if (isset($fruits[0])) {
echo "First fruit exists";
}
// ลบ element (index ไม่ reindex)
unset($fruits[2]);
print_r($fruits);
// [0 => "apple", 1 => "blueberry", 3 => "mango", ...]
// Reindex array
$fruits = array_values($fruits);

Arrays ที่ใช้ string เป็น key:

<?php
$person = [
"name" => "John",
"age" => 25,
"email" => "john@example.com",
"active" => true
];
// เข้าถึงด้วย key
echo $person["name"]; // "John"
echo $person["age"]; // 25
// เปลี่ยนค่า
$person["age"] = 26;
// เพิ่ม key ใหม่
$person["phone"] = "123-456-7890";
// ลบ key
unset($person["email"]);
// ตรวจสอบ key
if (array_key_exists("name", $person)) {
echo "Name exists";
}
// Null coalescing สำหรับ key ที่อาจไม่มี
$country = $person["country"] ?? "Unknown";
// ดึง keys และ values
$keys = array_keys($person); // ["name", "age", "active", "phone"]
$values = array_values($person); // ["John", 26, true, "123-456-7890"]

Arrays ซ้อน arrays:

<?php
// 2D Array
$matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
echo $matrix[0][0]; // 1
echo $matrix[1][2]; // 6
// Array of associative arrays
$users = [
[
"id" => 1,
"name" => "Alice",
"email" => "alice@example.com"
],
[
"id" => 2,
"name" => "Bob",
"email" => "bob@example.com"
],
[
"id" => 3,
"name" => "Charlie",
"email" => "charlie@example.com"
]
];
// เข้าถึง
echo $users[0]["name"]; // "Alice"
echo $users[2]["email"]; // "charlie@example.com"
// Loop
foreach ($users as $user) {
echo "{$user['name']}: {$user['email']}\n";
}
// Nested associative
$company = [
"name" => "TechCorp",
"departments" => [
"engineering" => [
"head" => "John",
"members" => ["Alice", "Bob", "Charlie"]
],
"marketing" => [
"head" => "Jane",
"members" => ["David", "Eve"]
]
]
];
echo $company["departments"]["engineering"]["head"]; // "John"
echo $company["departments"]["marketing"]["members"][0]; // "David"

<?php
// Basic destructuring
$data = [1, 2, 3];
[$a, $b, $c] = $data;
echo "$a, $b, $c"; // "1, 2, 3"
// ข้าม element
$data = [1, 2, 3, 4, 5];
[, $second, , $fourth] = $data;
echo "$second, $fourth"; // "2, 4"
// Swap values
$a = 1;
$b = 2;
[$a, $b] = [$b, $a];
echo "$a, $b"; // "2, 1"
// Associative destructuring (PHP 7.1+)
$person = ["name" => "John", "age" => 25, "city" => "Bangkok"];
["name" => $name, "age" => $age] = $person;
echo "$name is $age years old";
// ใน foreach
$users = [
["name" => "Alice", "age" => 30],
["name" => "Bob", "age" => 25],
];
foreach ($users as ["name" => $name, "age" => $age]) {
echo "$name: $age\n";
}
// Default values ไม่ได้โดยตรง ใช้ ?? แทน
$data = [1, 2];
[$a, $b, $c] = [...$data, null];
$c = $c ?? 0;

<?php
// รวม arrays
$first = [1, 2, 3];
$second = [4, 5, 6];
$merged = [...$first, ...$second];
// [1, 2, 3, 4, 5, 6]
// เพิ่ม elements
$base = [1, 2, 3];
$extended = [0, ...$base, 4, 5];
// [0, 1, 2, 3, 4, 5]
// Clone array
$original = [1, 2, 3];
$copy = [...$original];
// PHP 8.1+: Spread with string keys
$defaults = ["timeout" => 30, "retries" => 3];
$config = [...$defaults, "timeout" => 60];
// ["timeout" => 60, "retries" => 3]
// ใช้กับ function arguments
function sum(int ...$numbers): int {
return array_sum($numbers);
}
$numbers = [1, 2, 3, 4, 5];
echo sum(...$numbers); // 15

<?php
$arr = [1, 2, 3];
// เพิ่มท้าย
array_push($arr, 4, 5); // [1, 2, 3, 4, 5]
$arr[] = 6; // [1, 2, 3, 4, 5, 6]
// เพิ่มหน้า
array_unshift($arr, 0); // [0, 1, 2, 3, 4, 5, 6]
// ลบท้าย
$last = array_pop($arr); // $last = 6, $arr = [0, 1, 2, 3, 4, 5]
// ลบหน้า
$first = array_shift($arr); // $first = 0, $arr = [1, 2, 3, 4, 5]
// ลบด้วย index
unset($arr[2]); // ลบ index 2
$arr = array_values($arr); // reindex
<?php
$arr = [0, 1, 2, 3, 4, 5];
// Slice - ตัดย่อย (ไม่แก้ไข original)
$slice = array_slice($arr, 2, 3);
// [2, 3, 4] (เริ่ม index 2, เอา 3 ตัว)
$slice = array_slice($arr, -2);
// [4, 5] (2 ตัวสุดท้าย)
// Splice - ตัดและแทนที่ (แก้ไข original)
$removed = array_splice($arr, 2, 2, ["a", "b"]);
// $removed = [2, 3]
// $arr = [0, 1, "a", "b", 4, 5]
<?php
$fruits = ["apple", "banana", "orange", "banana"];
// ค้นหา value
in_array("banana", $fruits); // true
in_array("Banana", $fruits); // false (case-sensitive)
in_array("grape", $fruits); // false
// Strict search
in_array("1", [1, 2, 3]); // true (loose)
in_array("1", [1, 2, 3], true); // false (strict)
// หา index
array_search("banana", $fruits); // 1 (first occurrence)
array_search("grape", $fruits); // false
// หาทุก keys
array_keys($fruits, "banana"); // [1, 3]
// ตรวจสอบ key
array_key_exists("0", $fruits); // true
isset($fruits[0]); // true
<?php
$numbers = [3, 1, 4, 1, 5, 9, 2, 6];
$assoc = ["c" => 3, "a" => 1, "b" => 2];
// Sort values (แก้ไข original, reset keys)
sort($numbers); // [1, 1, 2, 3, 4, 5, 6, 9]
rsort($numbers); // [9, 6, 5, 4, 3, 2, 1, 1]
// Sort values (รักษา keys)
asort($assoc); // ["a" => 1, "b" => 2, "c" => 3]
arsort($assoc); // ["c" => 3, "b" => 2, "a" => 1]
// Sort by keys
ksort($assoc); // ["a" => 1, "b" => 2, "c" => 3]
krsort($assoc); // ["c" => 3, "b" => 2, "a" => 1]
// Natural sort
$files = ["img10.png", "img2.png", "img1.png"];
natsort($files); // ["img1.png", "img2.png", "img10.png"]
// Custom sort
$users = [
["name" => "Charlie", "age" => 30],
["name" => "Alice", "age" => 25],
["name" => "Bob", "age" => 35],
];
usort($users, fn($a, $b) => $a["age"] <=> $b["age"]);
// sort by age ascending
usort($users, fn($a, $b) => $b["age"] <=> $a["age"]);
// sort by age descending
usort($users, fn($a, $b) => strcmp($a["name"], $b["name"]));
// sort by name alphabetically
<?php
$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// Filter with callback
$evens = array_filter($numbers, fn($n) => $n % 2 === 0);
// [2, 4, 6, 8, 10] (รักษา keys)
$evens = array_values(array_filter($numbers, fn($n) => $n % 2 === 0));
// [2, 4, 6, 8, 10] (reset keys)
// Filter by key
$arr = ["a" => 1, "b" => 2, "c" => 3];
$filtered = array_filter($arr, fn($k) => $k !== "b", ARRAY_FILTER_USE_KEY);
// ["a" => 1, "c" => 3]
// Filter by both
$filtered = array_filter(
$arr,
fn($v, $k) => $v > 1 && $k !== "c",
ARRAY_FILTER_USE_BOTH
);
// ["b" => 2]
// Remove empty/falsy values
$data = ["hello", "", null, 0, "world", false];
$clean = array_filter($data); // ["hello", "world"]
<?php
$numbers = [1, 2, 3, 4, 5];
// Map ทุก element
$doubled = array_map(fn($n) => $n * 2, $numbers);
// [2, 4, 6, 8, 10]
// Map หลาย arrays
$a = [1, 2, 3];
$b = [10, 20, 30];
$sums = array_map(fn($x, $y) => $x + $y, $a, $b);
// [11, 22, 33]
// Map พร้อม keys
$users = ["alice" => 25, "bob" => 30, "charlie" => 35];
$result = array_map(
fn($name, $age) => "$name is $age",
array_keys($users),
array_values($users)
);
// ["alice is 25", "bob is 30", "charlie is 35"]
// Chaining map และ filter
$result = array_filter(
array_map(fn($n) => $n * 2, $numbers),
fn($n) => $n > 4
);
// [6, 8, 10]
<?php
$numbers = [1, 2, 3, 4, 5];
// Sum
$sum = array_reduce($numbers, fn($acc, $n) => $acc + $n, 0);
// 15
// Product
$product = array_reduce($numbers, fn($acc, $n) => $acc * $n, 1);
// 120
// Max (manual)
$max = array_reduce($numbers, fn($acc, $n) => max($acc, $n), PHP_INT_MIN);
// 5
// Build string
$words = ["Hello", "World", "!"];
$sentence = array_reduce($words, fn($acc, $w) => "$acc $w", "");
// " Hello World !"
$sentence = implode(" ", $words); // ง่ายกว่า
// "Hello World !"
// Group by
$items = [
["category" => "fruit", "name" => "apple"],
["category" => "fruit", "name" => "banana"],
["category" => "vegetable", "name" => "carrot"],
];
$grouped = array_reduce($items, function($acc, $item) {
$acc[$item["category"]][] = $item["name"];
return $acc;
}, []);
// ["fruit" => ["apple", "banana"], "vegetable" => ["carrot"]]
<?php
// Merge (รวม, values ซ้อนทับ)
$a = ["x" => 1, "y" => 2];
$b = ["y" => 3, "z" => 4];
$merged = array_merge($a, $b);
// ["x" => 1, "y" => 3, "z" => 4]
// Merge indexed arrays
$a = [1, 2, 3];
$b = [4, 5, 6];
$merged = array_merge($a, $b);
// [1, 2, 3, 4, 5, 6]
// Union (+) รักษาค่าจาก array แรก
$a = ["x" => 1, "y" => 2];
$b = ["y" => 3, "z" => 4];
$union = $a + $b;
// ["x" => 1, "y" => 2, "z" => 4]
// Combine keys และ values
$keys = ["a", "b", "c"];
$values = [1, 2, 3];
$combined = array_combine($keys, $values);
// ["a" => 1, "b" => 2, "c" => 3]
// Recursive merge
$a = ["config" => ["debug" => true, "cache" => true]];
$b = ["config" => ["debug" => false, "log" => true]];
$merged = array_merge_recursive($a, $b);
// ["config" => ["debug" => [true, false], "cache" => true, "log" => true]]

Array Functions สำหรับ Keys และ Values

Section titled “Array Functions สำหรับ Keys และ Values”
<?php
$person = ["name" => "John", "age" => 25, "city" => "Bangkok"];
// ดึง keys
$keys = array_keys($person);
// ["name", "age", "city"]
// ดึง values
$values = array_values($person);
// ["John", 25, "Bangkok"]
// กลับ keys และ values
$flipped = array_flip($person);
// ["John" => "name", 25 => "age", "Bangkok" => "city"]
// สร้าง array จาก column
$users = [
["id" => 1, "name" => "Alice"],
["id" => 2, "name" => "Bob"],
];
$names = array_column($users, "name");
// ["Alice", "Bob"]
$names = array_column($users, "name", "id");
// [1 => "Alice", 2 => "Bob"]
// Unique values
$arr = [1, 2, 2, 3, 3, 3];
$unique = array_unique($arr);
// [0 => 1, 1 => 2, 3 => 3]
$unique = array_values(array_unique($arr));
// [1, 2, 3]
// Count values
$votes = ["a", "b", "a", "c", "a", "b"];
$counts = array_count_values($votes);
// ["a" => 3, "b" => 2, "c" => 1]

แบบฝึกหัดที่ 1: Array Utilities

Section titled “แบบฝึกหัดที่ 1: Array Utilities”
<?php
// หาค่าที่ซ้ำกัน
function findDuplicates(array $arr): array {
$counts = array_count_values($arr);
return array_keys(array_filter($counts, fn($c) => $c > 1));
}
print_r(findDuplicates([1, 2, 2, 3, 3, 3, 4]));
// [2, 3]
// Chunk array
function customChunk(array $arr, int $size): array {
return array_chunk($arr, $size);
}
print_r(customChunk([1, 2, 3, 4, 5, 6, 7], 3));
// [[1, 2, 3], [4, 5, 6], [7]]

แบบฝึกหัดที่ 2: Group และ Pivot

Section titled “แบบฝึกหัดที่ 2: Group และ Pivot”
<?php
// Group by field
function groupBy(array $items, string $key): array {
return array_reduce($items, function($acc, $item) use ($key) {
$acc[$item[$key]][] = $item;
return $acc;
}, []);
}
$products = [
["name" => "iPhone", "category" => "phone"],
["name" => "Galaxy", "category" => "phone"],
["name" => "MacBook", "category" => "laptop"],
];
print_r(groupBy($products, "category"));

แบบฝึกหัดที่ 3: Array Diff และ Intersect

Section titled “แบบฝึกหัดที่ 3: Array Diff และ Intersect”
<?php
// หาความแตกต่าง
$a = [1, 2, 3, 4, 5];
$b = [3, 4, 5, 6, 7];
$onlyInA = array_diff($a, $b); // [1, 2]
$onlyInB = array_diff($b, $a); // [6, 7]
$common = array_intersect($a, $b); // [3, 4, 5]
// Symmetric difference (ค่าที่อยู่เฉพาะใน array ใดอันหนึ่ง)
$symmetric = array_merge(
array_diff($a, $b),
array_diff($b, $a)
);
// [1, 2, 6, 7]

PHP 8.4 เพิ่ม array functions ใหม่ที่มีประโยชน์มาก

<?php
/**
* array_find(array $array, callable $callback): mixed
* - หา element แรกที่ตรงเงื่อนไข
* - return ค่าที่พบ หรือ null ถ้าไม่พบ
*
* array_find_key(array $array, callable $callback): int|string|null
* - หา key แรกที่ตรงเงื่อนไข
* - return key ที่พบ หรือ null ถ้าไม่พบ
*/
$users = [
['id' => 1, 'name' => 'John', 'active' => false],
['id' => 2, 'name' => 'Jane', 'active' => true],
['id' => 3, 'name' => 'Bob', 'active' => true],
];
// หา user แรกที่ active
$activeUser = array_find($users, fn($u) => $u['active'] === true);
// ['id' => 2, 'name' => 'Jane', 'active' => true]
// หา key ของ user ที่ชื่อ Bob
$bobKey = array_find_key($users, fn($u) => $u['name'] === 'Bob');
// 2
// เทียบกับ PHP 8.3 และก่อนหน้า
// ต้องเขียนเอง
function array_find_polyfill(array $array, callable $callback): mixed {
foreach ($array as $item) {
if ($callback($item)) {
return $item;
}
}
return null;
}
<?php
/**
* array_any(array $array, callable $callback): bool
* - ตรวจสอบว่ามี element ใดๆ ที่ตรงเงื่อนไขหรือไม่
*
* array_all(array $array, callable $callback): bool
* - ตรวจสอบว่า ทุก element ตรงเงื่อนไขหรือไม่
*/
$numbers = [2, 4, 6, 8, 10];
// ตรวจสอบว่ามีเลขคี่หรือไม่
$hasOdd = array_any($numbers, fn($n) => $n % 2 !== 0);
// false
// ตรวจสอบว่าเป็นเลขคู่ทั้งหมดหรือไม่
$allEven = array_all($numbers, fn($n) => $n % 2 === 0);
// true
// ตัวอย่างใช้งานจริง: validate data
$users = [
['email' => 'john@example.com', 'verified' => true],
['email' => 'jane@example.com', 'verified' => true],
['email' => 'bob@example.com', 'verified' => false],
];
// มี user ที่ยังไม่ verify หรือไม่
$hasUnverified = array_any($users, fn($u) => !$u['verified']);
// true
// user ทุกคน verify แล้วหรือยัง
$allVerified = array_all($users, fn($u) => $u['verified']);
// false
// Polyfill สำหรับ PHP 8.3 และก่อนหน้า
function array_any_polyfill(array $array, callable $callback): bool {
foreach ($array as $item) {
if ($callback($item)) {
return true;
}
}
return false;
}
function array_all_polyfill(array $array, callable $callback): bool {
foreach ($array as $item) {
if (!$callback($item)) {
return false;
}
}
return true;
}

<?php
// ดี: short syntax
$fruits = ['apple', 'banana', 'orange'];
$person = ['name' => 'John', 'age' => 25];
// ไม่แนะนำ: array() syntax (PHP 5.3 และก่อนหน้า)
$fruits = array('apple', 'banana', 'orange');
<?php
/**
* ใช้ PHPDoc สำหรับ array types ที่ซับซ้อน
*
* @param array<int, string> $names
* @param array<string, mixed> $config
* @return array{name: string, age: int}
*/
function processData(array $names, array $config): array {
// ...
return ['name' => 'John', 'age' => 25];
}
// PHP 8+ typed properties
class UserRepository
{
/** @var array<int, User> */
private array $users = [];
}

3. หลีกเลี่ยง Reference ถ้าไม่จำเป็น

Section titled “3. หลีกเลี่ยง Reference ถ้าไม่จำเป็น”
<?php
// ไม่แนะนำ: ใช้ reference โดยไม่จำเป็น
foreach ($items as &$item) {
$item = processItem($item);
}
unset($item); // ต้องจำ unset!
// ดีกว่า: ใช้ array_map
$items = array_map(fn($item) => processItem($item), $items);
// หรือถ้าต้องการ modify in place
foreach ($items as $key => $item) {
$items[$key] = processItem($item);
}

4. ใช้ Null Coalescing สำหรับ Array Access

Section titled “4. ใช้ Null Coalescing สำหรับ Array Access”
<?php
$config = ['debug' => true, 'cache' => ['ttl' => 3600]];
// ดี: ใช้ ?? สำหรับ default value
$debug = $config['debug'] ?? false;
$ttl = $config['cache']['ttl'] ?? 300;
$host = $config['database']['host'] ?? 'localhost';
// ไม่ดี: ต้องตรวจสอบ isset ก่อน
if (isset($config['debug'])) {
$debug = $config['debug'];
} else {
$debug = false;
}

5. ใช้ First-Class Callable Syntax (PHP 8.1+)

Section titled “5. ใช้ First-Class Callable Syntax (PHP 8.1+)”
<?php
class StringHelper
{
public static function toUpperCase(string $str): string
{
return strtoupper($str);
}
}
$names = ['john', 'jane', 'bob'];
// PHP 8.1+: First-Class Callable Syntax
$upper = array_map(StringHelper::toUpperCase(...), $names);
// ['JOHN', 'JANE', 'BOB']
// PHP 8.0 และก่อนหน้า
$upper = array_map([StringHelper::class, 'toUpperCase'], $names);

ปัญหาที่พบบ่อยและวิธีแก้ไข

Section titled “ปัญหาที่พบบ่อยและวิธีแก้ไข”

1. Array Keys ไม่ต่อเนื่องหลัง unset()

Section titled “1. Array Keys ไม่ต่อเนื่องหลัง unset()”
<?php
$arr = [0 => 'a', 1 => 'b', 2 => 'c', 3 => 'd'];
unset($arr[1], $arr[2]);
print_r($arr);
// [0 => 'a', 3 => 'd'] // keys ไม่ต่อเนื่อง!
// วิธีแก้: ใช้ array_values() เพื่อ reindex
$arr = array_values($arr);
print_r($arr);
// [0 => 'a', 1 => 'd'] // keys ต่อเนื่องแล้ว
<?php
$arr = [0, false, null, ''];
// อันตราย! loose comparison
var_dump(in_array('', $arr)); // true ('' == null)
var_dump(in_array(false, $arr)); // true
// ปลอดภัย: ใช้ strict = true
var_dump(in_array('', $arr, true)); // true (มี '' จริงๆ)
var_dump(in_array('hello', $arr, true)); // false
<?php
$a = [0 => 'a', 1 => 'b'];
$b = [0 => 'c', 1 => 'd'];
// array_merge reindex numeric keys
$merged = array_merge($a, $b);
// [0 => 'a', 1 => 'b', 2 => 'c', 3 => 'd']
// + operator preserves keys (takes first value)
$combined = $a + $b;
// [0 => 'a', 1 => 'b'] // keys จาก $b ถูกทิ้ง!
// ถ้าต้องการ overwrite ใช้ ...spread
$merged = [...$a, ...$b];
// [0 => 'c', 1 => 'd'] // $b overwrite $a
<?php
$items = ['a', 'b', 'c', 'd', 'e'];
// อันตราย! modify while iterating
foreach ($items as $key => $item) {
if ($item === 'c') {
unset($items[$key]); // อาจมี unexpected behavior
}
}
// ปลอดภัยกว่า: ใช้ array_filter
$items = array_filter($items, fn($item) => $item !== 'c');
// หรือเก็บ keys ที่จะลบก่อน
$toRemove = [];
foreach ($items as $key => $item) {
if (shouldRemove($item)) {
$toRemove[] = $key;
}
}
foreach ($toRemove as $key) {
unset($items[$key]);
}
<?php
$arr = [1, 2, 3];
// อันตราย! $item เป็น reference
foreach ($arr as &$item) {
$item *= 2;
}
// $item ยังคง reference ไปที่ $arr[2]!
$item = 100; // เปลี่ยนค่า $arr[2] ด้วย!
print_r($arr); // [2, 4, 100]
// วิธีแก้: unset reference หลัง loop
foreach ($arr as &$item) {
$item *= 2;
}
unset($item); // อย่าลืม!

1. isset() เร็วกว่า array_key_exists()

Section titled “1. isset() เร็วกว่า array_key_exists()”
<?php
$arr = ['key' => null];
// isset() เร็วกว่าแต่ return false สำหรับ null values
isset($arr['key']); // false (เพราะ value เป็น null)
// array_key_exists() ช้ากว่าแต่แม่นยำกว่า
array_key_exists('key', $arr); // true
// ใช้ isset() เมื่อไม่ต้องการแยก null กับ undefined
// ใช้ array_key_exists() เมื่อ null เป็นค่าที่ valid

2. Pre-allocate Array ถ้ารู้ขนาด

Section titled “2. Pre-allocate Array ถ้ารู้ขนาด”
<?php
// ไม่ดี: array grow ทีละตัว
$result = [];
for ($i = 0; $i < 10000; $i++) {
$result[] = $i * 2;
}
// ดีกว่า: ใช้ array_map
$result = array_map(fn($i) => $i * 2, range(0, 9999));
// หรือถ้าต้องการ pre-allocate
$result = array_fill(0, 10000, 0);
for ($i = 0; $i < 10000; $i++) {
$result[$i] = $i * 2;
}

3. ใช้ Generator สำหรับ Large Arrays

Section titled “3. ใช้ Generator สำหรับ Large Arrays”
<?php
// ไม่ดี: โหลดทั้งหมดเข้า memory
function getAllUsers(): array {
$users = [];
foreach (fetchFromDatabase() as $row) {
$users[] = new User($row);
}
return $users; // อาจใช้ memory หลาย GB!
}
// ดีกว่า: ใช้ Generator
function getAllUsersGenerator(): Generator {
foreach (fetchFromDatabase() as $row) {
yield new User($row); // ใช้ memory น้อยมาก
}
}
// ใช้งาน
foreach (getAllUsersGenerator() as $user) {
processUser($user);
}

ในบทนี้เราได้เรียนรู้:

  • การสร้าง indexed, associative และ multidimensional arrays
  • Array destructuring และ spread operator
  • Functions: push, pop, shift, unshift, slice, splice
  • Searching: in_array, array_search, array_key_exists
  • Sorting: sort, usort, ksort
  • Filtering และ mapping: array_filter, array_map
  • Reducing: array_reduce
  • Merging: array_merge, union (+), array_combine
  • Key/Value functions: array_keys, array_values, array_column
  • PHP 8.4+ functions: array_find, array_find_key, array_any, array_all
  • Best practices และ performance tips

แหล่งข้อมูลเพิ่มเติม

Section titled “แหล่งข้อมูลเพิ่มเติม”

เข้าสู่ระบบเพื่อดูเนื้อหาเต็ม

ยืนยันตัวตนด้วยบัญชี Google เพื่อปลดล็อกบทความทั้งหมด