หลายครั้งที่ต้องการกรอง Key ของ Array เฉพาะที่ขึ้นต้นด้วย Prefix ที่กำหนด (เช่น test_, foo-) PHP มีหลายวิธีทำ ให้เลือกใช้ตาม Version และความชอบ
วิธีที่ 1: ใช้ foreach + strpos (รองรับทุก Version, เข้าใจง่าย)
$array = [
'test_val' => 123,
'other-value' => 456,
'test_result' => 789,
'foo_bar' => 999
];
$prefix = 'test_';
$result = [];
foreach ($array as $key => $value) {
if (strpos($key, $prefix) === 0) { // === 0 หมายถึงขึ้นต้นด้วย
$result[$key] = $value;
}
}
print_r($result);
// Array ( [test_val] => 123 [test_result] => 789 )
วิธีที่ 2: ใช้ array_filter (PHP 5.6+, Functional Style)
$prefix = 'test_';
$result = array_filter($array, function($key) use ($prefix) {
return strpos($key, $prefix) === 0;
}, ARRAY_FILTER_USE_KEY);
print_r($result);
วิธีที่ 3: ใช้ array_filter + fn (PHP 7.4+, Arrow Function)
$prefix = 'test_';
$result = array_filter($array, fn($key) => strpos($key, $prefix) === 0, ARRAY_FILTER_USE_KEY);
วิธีที่ 4: ใช้ Regex (กรณี Pattern ซับซ้อน)
$pattern = '/^test_/'; // เริ่มต้นด้วย test_
$result = array_filter($array, function($key) use ($pattern) {
return preg_match($pattern, $key);
}, ARRAY_FILTER_USE_KEY);
วิธีที่ 5: ใช้ ArrayIterator (Object-oriented, Memory Efficient สำหรับ Array ใหญ่)
$iterator = new ArrayIterator($array);
$result = [];
foreach ($iterator as $key => $value) {
if (strpos($key, 'test_') === 0) {
$result[$key] = $value;
}
}
Benchmark: วิธีไหนเร็วที่สุด? (Array 100,000 รายการ)
$array = array_combine(
array_map(fn($i) => ($i % 3 === 0 ? 'test_' : 'other_') . $i, range(1, 100000)),
range(1, 100000)
);
// วิธีที่ 1: foreach loop
$start = microtime(true);
$result1 = [];
foreach ($array as $k => $v) {
if (strpos($k, 'test_') === 0) $result1[$k] = $v;
}
echo "foreach: " . (microtime(true) - $start) . "s\n";
// วิธีที่ 2: array_filter
$start = microtime(true);
$result2 = array_filter($array, fn($k) => strpos($k, 'test_') === 0, ARRAY_FILTER_USE_KEY);
echo "array_filter: " . (microtime(true) - $start) . "s\n";
/* ผลลัพธ์ประมาณ:
foreach: 0.008s
array_filter: 0.012s
*/
// foreach เร็วกว่าเล็กน้อย และอ่านง่าย
คำแนะนำ
- โปรเจกต์ทั่วไป: ใช้ foreach (อ่านง่าย, เร็ว, รองรับทุก Version)
- Functional Programming: ใช้ array_filter + Arrow Function (PHP 7.4+)
- Pattern ซับซ้อน: ใช้ Regex ด้วย preg_match
- Array ใหญ่มาก (Memory): ใช้ Generator หรือ ArrayIterator