|
 |
|
ใช้ explode แล้วไม่เจอค่าที่ต้องการจะ error อยากทราบวิธีแก้ไขหน่อยครับ |
|
 |
|
|
 |
 |
|
ก่อนใช้ $e[1] ก็ต้องเช็คค่าก่อนว่ามีอยู่หรือไม่
จะใช้ isset หรือ empty, ... ก็ว่าไป
|
 |
 |
 |
 |
Date :
2022-06-16 21:15:57 |
By :
009 |
|
 |
 |
 |
 |
|
|
 |
 |
|
 |
 |
 |
|
|
 |
 |
|
Quote:Undefined array key
Quote:คีย์อาร์เรย์ที่ไม่ได้กำหนด
ตัวอย่างที่จะทำให้เกิด error นี้
Code (PHP)
$array = [
'region' => 'Asia',
];
$array['country'];// error
$numbers = [0, 3, 4];
$numbers[4];// error เพราะมีแค่ 0 (0), 1 (3), 2 (4)
วิธีป้องกัน ใช้ได้ทั้ง isset(), array_key_exists() ตามจุดประสงค์ที่แตกต่างกันไป
ตัวอย่าง
Code (PHP)
$array = [
0 => '',
1 => false,
2 => true,
3 => null,
4 => [],
5 => new \stdClass(),
];
var_dump(isset($array[0]));// true
var_dump(isset($array[1]));// true
var_dump(isset($array[2]));// true
var_dump(isset($array[3]));// false
var_dump(isset($array[4]));// true
var_dump(isset($array[5]));// true
var_dump(isset($array[99]));// false
echo '<hr>' . PHP_EOL;
var_dump(array_key_exists(0, $array));// true
var_dump(array_key_exists(1, $array));// true
var_dump(array_key_exists(2, $array));// true
var_dump(array_key_exists(3, $array));// true
var_dump(array_key_exists(4, $array));// true
var_dump(array_key_exists(5, $array));// true
var_dump(array_key_exists(99, $array));// false
ให้สังเกตุเอาให้ดีๆ มันจะมีความต่างกันอยู่.
ทีนี้การใช้ ถ้าจะใช้ isset() มันจะมีคำสั่งเต็มแบบนี้
Code (PHP)
if (isset($array[1])) {
echo $array[1];
} else {
echo '';
}
กับคำสั่งบรรทัดเดียว
Code (PHP)
echo (isset($array[1]) ? $array[1] : '');
และคำสั่งบรรทัดเดียวสำหรับ PHP 7+ ที่เรียกว่า Null coalescing.
Code (PHP)
echo ($array[1] ?? '');
ทั้ง 3 แบบข้างบนนี้มีค่าเท่ากันทำงานเหมือนกัน
parse_url()
ถ้าจะทำงานกับ URL แนะนำให้ใช้ฟังก์ชั่นนี้จะดีกว่า เพราะมันสำหรับงานนี้โดยตรง.
parse_url()
ให้ดูเอกสารประกอบ.
|
 |
 |
 |
 |
Date :
2022-06-16 22:34:39 |
By :
mr.v |
|
 |
 |
 |
 |
|
|
 |
 |
|
 |
 |
|
|
|

|
Load balance : Server 02
|