32
29

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Last updated at Posted at 2014-04-11

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を返す。

32
29
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
32
29

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?