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 を利用しても配列の存在チェックができる。


    // 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を返すが、

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