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

PHP 配列の要素の存在チェックにおける array_key_exist() と isset() の違い

More than 5 years have passed since last update.

array_key_exists ではなく、isset を利用しても配列の存在チェックができる。
ただ両者では挙動に違いがあるので注意が必要。

サンプルコード

<?php
    // array_key_exists と isset を利用した配列の存在チェック
    function check($key, $array)
    {
        $ret1 = array_key_exists($key, $array) ? "Exist" : "Not Exist";
        $ret2 = isset($array[$key]) ? "Exist" : "Not Exist";
        echo "$key exist check : array_key_exists() = $ret1 / isset() = $ret2" . PHP_EOL;
    }

    $array = array("key1" => "value1", "key2" => null);

    check("key1", $array);
    check("key2", $array);
    check("key3", $array);

実行結果

$ php test.php
key1 exist check : array_key_exists= Exist / isset= Exist
key2 exist check : array_key_exists= Exist / isset= Not Exist
key3 exist check : array_key_exists= Not Exist / isset= Not Exist

array_key_exists() は配列中にKey値が存在すれば値が何であろうがTRUEを返すが、
issetの場合、Key値が存在してもその値がNULLであった場合、FALSEを返す。

Why do not you register as a user and use Qiita more conveniently?
  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