PHP Undefined offset エラー
作成日時:2019/06/14
更新日時:2019/06/14
スポンサーリンク
    この記事の確認環境
phpversion() : 7.2.7
エラー概要
配列から未定義のインデックスの要素を取得しようとすると発生します。
エラーメッセージ
PHP Notice: Undefined index
Noticeが発生するコード例
配列から未定義のインデックスの要素を取得しようとする
<?php
$test_array = array('apple', 'banana');
$test = $test_array[2];
    Noticeの回避方法
isset()を使用し値が設定されていない場合は取得しないようにする
isset() - https://php.net/manual/ja/function.isset.php
<?php
$test_array = array('apple', 'banana');
$test = isset($test_array[2]) ? $test_array[2] : 'Undef';
    array_key_exists()を使用し未定義のインデックスの場合は取得しないようにする
array_key_exists() - https://php.net/manual/ja/function.array-key-exists.php
<?php
$test_array = array('apple', 'banana');
$test = array_key_exists(2, $test_array) ? $test_array[2] : 'Undef';