Help us understand the problem. What is going on with this article?

多次元配列のisset() は一気にチェックできる

More than 1 year has passed since last update.

isset() 関数で多次元配列のキー存在チェックをする際、たまに

<?php
if (isset($a) && isset($a['foo']) && isset($a['foo']['bar'])) {
    // do something
}

と、上から丁寧にチェックしているソースを見かけますが
この場合、途中のチェックは不要で

<?php
if (isset($a['foo']['bar'])) {
    // do something
}

とだけ書けば大丈夫です。

検証ソース

test.php
<?php
error_reporting(E_ALL);

var_dump(isset($a['foo']['bar']));

$a = array();
var_dump(isset($a['foo']['bar']));

$a['foo'] = array();
var_dump(isset($a['foo']['bar']));

$a['foo']['bar'] = 1;
var_dump(isset($a['foo']['bar']));

実行結果

$ php test.php
bool(false)
bool(false)
bool(false)
bool(true)

途中 $a$a['foo'] が未定義でも、Undefined variable の Noticeはでません。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away