at 6:18 AM

php: array_key_exists or isset

I know array_key_exists is a function and isset is a keyword, later, i think array_key_exists and isset in PHP is a same or array_key_exists is shortcut for isset. But when i read  on php manual, there is no document that explains that it is the same or related, so i try to look in php source code, and i got the same answers.
In my mind, array_key_exists is like that :)
boolean array_key_exists (key, arrayName) {
    return isset(arrayName[key]);
}


and this is code for array_key_exists which i look in php source code.
/* {{{ proto bool array_key_exists(mixed key, array search)
   Checks if the given key or index exists in the array */
PHP_FUNCTION(array_key_exists)
{
 zval *key;     /* key to check for */
 HashTable *array;   /* array to check in */

 if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zH", &key, &array) == FAILURE) {
  return;
 }

 switch (Z_TYPE_P(key)) {
  case IS_STRING:
   if (zend_symtable_exists(array, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1)) {
    RETURN_TRUE;
   }
   RETURN_FALSE;
  case IS_LONG:
   if (zend_hash_index_exists(array, Z_LVAL_P(key))) {
    RETURN_TRUE;
   }
   RETURN_FALSE;
  case IS_NULL:
   if (zend_hash_exists(array, "", 1)) {
    RETURN_TRUE;
   }
   RETURN_FALSE;

  default:
   php_error_docref(NULL TSRMLS_CC, E_WARNING, "The first argument should be either a string or an integer");
   RETURN_FALSE;
 }
}

yeah, its really different.

Difference.
So what the big different between them, this is the list based in my mind and other source from internet.


  1. isset is keyword or language constructor and array_key_exists is function.
    so isset faster then array_key_exists.
  2. isset will check value of variables.
    if value of variable is null isset will return false, but with array_key_exists will return true even a value is null.
    $ php -r '$var=array("php"=>null); var_dump(isset($var["php"]));'
    (bool)false
    $ php -r '$var=array("php"=>null); var_dump(array_key_exists("php", $var));'
    (bool)true
    

Source:



Tulis Komentar dengan akun Facebook Anda.

0 comments:

Post a Comment