PHP Undefined Index 오류 완벽 해결

프리터코더·2025년 5월 25일

php 문제 해결

목록 보기
3/79

문제 설명

Undefined Index 오류는 PHP에서 존재하지 않는 배열 키나 인덱스에 접근할 때 발생하는 일반적인 오류입니다.

해결 방법

1. isset() 함수 사용

if (isset($_POST['username'])) {
    $username = $_POST['username'];
} else {
    $username = '';
}

2. 널 병합 연산자 사용 (PHP 7.0+)

$username = $_POST['username'] ?? '';
$email = $_GET['email'] ?? 'default@example.com';

3. 배열 키 존재 여부 확인

$config = [];
$dbHost = array_key_exists('db_host', $config) ? $config['db_host'] : 'localhost';

4. 폼 데이터 처리 예시

$name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING) ?? '';
$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL) ?? '';

베스트 프랙티스

1. 기본값 설정

$settings = [
    'title' => 'Default Title',
    'theme' => 'light',
    'language' => 'en'
];

$userSettings = array_merge($settings, $customSettings);

2. 타입 체크 추가

function getValue($array, $key, $default = null) {
    return is_array($array) && isset($array[$key]) ? $array[$key] : $default;
}

3. 전역 변수 처리

$GLOBALS['config'] = [
    'debug' => true,
    'environment' => 'development'
];

성능 최적화 팁

  • 배열 키 접근 전 항상 검증
  • 불필요한 검사 최소화
  • 캐싱 활용

디버깅 도구

  • XDebug 사용
  • PHP Debug Bar 활용
  • 로깅 구현
profile
일용직 개발자. freetercoder@gmail.com

0개의 댓글