So unless you need to check if a key exists in an array with null being a valid value, you can use either function. isset() is also more readable than array_key_exists(). Isset() is 1.08x faster than array_key_exists() because it is a language construct and array_key_exists() is a function. Let’s check out the performance of both functions, by looping over an array 1,000,000 times and checking if a key exists in the array. Which Is Faster: isset() or array_key_exists()? The isset () function will generate a warning or e-notice when the variable does not exists. The empty () function is an inbuilt function in PHP that is used to check whether a variable is empty or not. Var_dump(array_key_exists('key1', $array_with_null_value)) // trueĪs you can see, the only difference between isset() and array_key_exists() occurs when evaluating the array with a null value.Įvaluating an empty array, an array with or without a key, or an array with an empty string will return the same result for both isset() and array_key_exists(). The isset () function is an inbuilt function in PHP that is used to determine if the variable is declared and its value is not equal to NULL. Var_dump(isset($array_with_null_value)) // false Test 4: isset() vs array_key_exists() with array with null value Var_dump(array_key_exists('key1', $array_with_empty_string)) // true Var_dump(isset($array_with_empty_string)) // true Test 3: isset() vs array_key_exists() with array with empty string Var_dump(array_key_exists('key1', $test_array)) // true Test 2: isset() vs array_key_exists() with array with key Var_dump(array_key_exists('key1', $empty_array)) // false Test 1: isset() vs array_key_exists() with empty array While isset() and array_key_exists() can both be used to check if a key exists in an array, and will return the same result in most cases, isset() will return false if the value of the key is null, while array_key_exists() will return true.Ĭheck out the example below: $empty_array = Let’s take a look at the difference between the two. Yet, there’s a situation where they don’t. On the surface, isset() and array_key_exists() seem to do the exact same thing.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |