728x90
반응형
📌 PHP Undefined Index / Variable 에러 원인과 해결 방법
PHP 코드를 실행했을 때, 다음과 같은 경고 메시지를 본 적 있으신가요?
Notice: Undefined index: name in /var/www/html/index.php on line 5
Notice: Undefined variable: email in /var/www/html/register.php on line 8
이 메시지는 존재하지 않는 변수 또는 배열 키에 접근하려고 했을 때 발생하는 PHP Notice입니다.
🧨 에러 원인
- Undefined variable: 변수가 선언되지 않았는데 접근하려 할 때 발생
- Undefined index: 배열에 존재하지 않는 키에 접근하려 할 때 발생
<?php
echo $username; // undefined variable
echo $_POST['email']; // email이 없는 경우 undefined index
?>
🛠 해결 방법
1. isset() 또는 empty()로 체크
변수나 배열 키가 존재하는지 먼저 확인하는 습관을 들이세요:
<?php
if (isset($_POST['email'])) {
$email = $_POST['email'];
} else {
$email = '';
}
?>
2. null 병합 연산자 사용 (PHP 7+)
<?php
$email = $_POST['email'] ?? '';
?>
3. 기본값 설정 함수 사용
<?php
function get_value($array, $key, $default = '') {
return isset($array[$key]) ? $array[$key] : $default;
}
$email = get_value($_POST, 'email');
?>
✅ 정리
에러 유형 | 원인 | 해결법 |
---|---|---|
Undefined variable | 선언되지 않은 변수에 접근 | isset() 또는 초기화 |
Undefined index | 배열에 없는 키에 접근 | isset(), ?? 연산자 등 활용 |
📚 관련 글
- PHP include 에러 해결법 - Failed to open stream
- Call to undefined function 에러 처리법
- headers already sent 에러 해결 가이드
728x90
반응형
'PHP > PHP 에러 해결 모음' 카테고리의 다른 글
PHP Parse error: unexpected token 에러 해결 가이드 (0) | 2025.04.09 |
---|---|
PHP Header 에러 해결법 - Cannot modify header information 경고의 원인과 대처법 (0) | 2025.04.09 |
PHP include 에러 해결법 - Failed to open stream 원인과 해결 방법 (0) | 2025.04.08 |
PHP 실행 시간 초과 에러 (Maximum execution time) 원인과 해결 방법 (0) | 2025.04.08 |
PHP Call to undefined function 에러 원인과 해결 방법 총정리 (0) | 2025.04.08 |