Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between isset() and array_key_exists()? [duplicate]

Tags:

php

How do the following two function calls compare:

isset($a['key'])  array_key_exists('key', $a) 
like image 681
Zacky112 Avatar asked Jul 09 '10 08:07

Zacky112


People also ask

What's the difference between isset () and array_key_exists ()?

Difference between isset() and array_key_exists() Function: The main difference between isset() and array_key_exists() function is that the array_key_exists() function will definitely tells if a key exists in an array, whereas isset() will only return true if the key/variable exists and is not null.

What is an isset () function?

The isset() function checks whether a variable is set, which means that it has to be declared and is not NULL. This function returns true if the variable exists and is not NULL, otherwise it returns false.

How do you use an isset in an array?

If you want to know whether the array is defined at all, use isset($array) . If you want to know whether a particular key is defined, use isset($array[$key]) .

Why is Isset used?

The isset function in PHP is used to determine whether a variable is set or not. A variable is considered as a set variable if it has a value other than NULL. In other words, you can also say that the isset function is used to determine whether you have used a variable in your code or not before.


1 Answers

array_key_exists will definitely tell you if a key exists in an array, whereas isset will only return true if the key/variable exists and is not null.

$a = array('key1' => 'フーバー', 'key2' => null);  isset($a['key1']);             // true array_key_exists('key1', $a);  // true  isset($a['key2']);             // false array_key_exists('key2', $a);  // true 

There is another important difference: isset doesn't complain when $a does not exist, while array_key_exists does.

like image 121
deceze Avatar answered Sep 26 '22 08:09

deceze