12.

【Laravelエラー】Illegal offset type

編集
この記事の要点
  • Illegal offset type配列のキーとして許されない型(オブジェクト・配列・null)を使った時のエラー
  • PHP の配列キーは int / string のみ許可
  • 原因 ①: $arr[$obj] のようにオブジェクトをキーに使った
  • 原因 ②: $arr[null]$arr[$array]
  • 対処: キーを (string) / spl_object_hash($obj) 等で文字列化、または SplObjectStorage を使う

 

エラーの状況

// Warning: Illegal offset type in xxx.php on line N
$arr = [];
$obj = new stdClass();
$arr[$obj] = "value";   // ← オブジェクトをキーに → エラー

$key = null;
$arr[$key] = "value";   // ← null も場合により警告

$arrKey = ["a", "b"];
$arr[$arrKey] = "x";    // ← 配列をキーに → エラー

PHP の連想配列のキーは 整数 (int) または文字列 (string) しか使えません。それ以外の型を渡すと Illegal offset type 警告が発生します。

PHP の配列キーで許される / 許されない型

キーとして挙動
intそのまま整数キー
stringそのまま文字列キー(数字のみなら int に自動変換)
float小数点切り捨てで int 変換(PHP 8.1+ で非推奨)
booltrue → 1, false → 0 に変換
null空文字列 "" に変換
array×Illegal offset type 警告
object×Illegal offset type 警告
resource×Illegal offset type 警告

対処方法

方法 1: オブジェクトを ID 化して文字列キーに

$obj = new stdClass();
$key = spl_object_hash($obj);  // 一意な文字列ハッシュ
$arr[$key] = "value";

// または ID 文字列を自分で作る
$key = get_class($obj) . "_" . spl_object_id($obj);
$arr[$key] = "value";

方法 2: オブジェクトのプロパティをキーにする

class User {
    public int $id;
    public string $name;
}

$user = new User();
$user->id = 123;
$user->name = "Alice";

// id をキーにする
$arr[$user->id] = $user;  // OK

方法 3: SplObjectStorage を使う(オブジェクトをキーにできる Map)

$storage = new SplObjectStorage();

$obj1 = new stdClass();
$obj2 = new stdClass();

$storage[$obj1] = "value1";  // OK
$storage[$obj2] = "value2";  // OK

// 取得
echo $storage[$obj1];  // "value1"

// 存在チェック
if (isset($storage[$obj1])) { ... }

// 削除
unset($storage[$obj1]);

// イテレート
foreach ($storage as $obj) {
    $value = $storage[$obj];
}

方法 4: 配列キーには文字列に変換

// 配列をキーにしたい場合は JSON 文字列化
$arrKey = ["category" => "books", "year" => 2026];
$key = json_encode($arrKey);
$arr[$key] = "value";  // OK

// または implode
$arrKey = ["books", 2026];
$key = implode("_", $arrKey);
$arr[$key] = "value";  // "books_2026"

よくある発生シーン

シーン 1: SimpleXML や DOM オブジェクトをキーに

$xml = simplexml_load_file("data.xml");
foreach ($xml->item as $item) {
    $arr[$item] = $item->value;  // ← SimpleXMLElement はオブジェクト → エラー
}

// 修正
foreach ($xml->item as $item) {
    $arr[(string)$item->id] = (string)$item->value;
}

シーン 2: フォームから受け取った配列をキーに

// $_POST["categories"] が配列の場合
$key = $_POST["categories"];   // 配列
$arr[$key] = "value";          // ← Illegal offset type

// 修正
foreach ($_POST["categories"] as $cat) {
    $arr[$cat] = "value";
}

シーン 3: 関数の戻り値が想定外

function getKey() {
    return new stdClass();  // 本来 string を返すべきだった
}

$arr[getKey()] = "value";  // ← エラー

// 修正: 関数の実装を見直すか、結果を変換
$result = getKey();
$key = is_object($result) ? spl_object_hash($result) : (string)$result;
$arr[$key] = "value";

PHP 8 以降での厳格化

PHP 8.0+ では、以前は警告だった一部の操作がエラーになっています:

  • PHP 7.x: Warning として警告、処理は続行(キーは無視)
  • PHP 8.0+: TypeError として例外、処理が止まる
// PHP 8 での捕捉
try {
    $arr[$obj] = "value";
} catch (TypeError $e) {
    // ハンドリング
}

関連エラー

  • Undefined offset / Undefined index: 存在しないキーで参照
  • Cannot use object of type X as array: オブジェクトを配列扱い
  • Trying to access array offset on value of type null: null を配列扱い
  • Illegal string offset: 文字列を連想配列扱い

関連記事

編集
Post Share
子ページ

子ページはありません

同階層のページ
  1. SQLSTATE[HY000] [1045] Access denied for user 'homestead'@'localhost'
  2. Add [~] to fillable property to allow mass assignment on [App\~].
  3. PHP Parse error: syntax error, unexpected 'class' (T_CLASS), expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$' in ~
  4. Changing columns for table "~" requires Doctrine DBAL; install "doctrine/dbal"
  5. MethodNotAllowedHttpException No message
  6. Class 'Doctrine\DBAL\Driver\PDOMySql\Driver' not found
  7. production.ERROR: No application encryption key has been specified.
  8. Dotenv values containing spaces must be surrounded by quotes.
  9. Laravel \ Socialite \ Two \ InvalidStateException
  10. The page has expired due to inactivity. Please refresh and try again.
  11. Failed to clone https://github.com/symfony/thanks.git via https, ssh protocol
  12. Illegal offset type
  13. Cannot access protected property Illuminate\Http\Request::$...
  14. Emitted value instead of an instance of Error
  15. 画像保存時にInternal Server Error
  16. Failed to authenticate on SMTP server with username ...
  17. PostTooLargeException
  18. Database hosts array is empty.
  19. Invalid request (Unsupported SSL request)
  20. does not comply with psr-4 autoloading standard. Skipping.
  21. MySQLのSTR_TO_DATE関数を使用するとnullが返却される問題