Arrays with NULL keys

后端 未结 3 496
鱼传尺愫
鱼传尺愫 2020-12-10 10:27

PHP trivia here.

If we declare an array like this:

 \'bar\', NULL => \'hello\' ]; ?>

We can ac

相关标签:
3条回答
  • 2020-12-10 10:41

    I have found the possibility to have Null keys useful, when accessing db, using a class, which can use one of the column values as the key to the returned array. Some column values could be null.

    0 讨论(0)
  • 2020-12-10 10:53

    Quote from the manual:

    Null will be cast to the empty string, i.e. the key null will actually be stored under "".

    Additional details about how keys are cast are as follows:

    The key can either be an integer or a string. The value can be of any type.

    Additionally the following key casts will occur:

    • Strings containing valid decimal integers, unless the number is preceded by a + sign, will be cast to the integer type. E.g. the key "8" will actually be stored under 8. On the other hand "08" will not be cast, as it isn't a valid decimal integer.
    • Floats are also cast to integers, which means that the fractional part will be truncated. E.g. the key 8.7 will actually be stored under 8.
    • Bools are cast to integers, too, i.e. the key true will actually be stored under 1 and the key false under 0.
    • Null will be cast to the empty string, i.e. the key null will actually be stored under "".
    • Arrays and objects can not be used as keys. Doing so will result in a warning: Illegal offset type.

    As for this being useful or necessary, this is debatable. You are asked to use integer or string keys and you have been warned about implicit key casting.

    0 讨论(0)
  • 2020-12-10 10:54

    Given a form API populated by an associative php array, I have found it useful to use a null-keyed value to indicate the NULL value in a database. E.g.:

    $this->addElement('select', 'foreignkey_id', array(
      'label'=>'Add a Poll',
      'multiOptions' => array(
          null => 'No value selected',
          '0' => 'Element with ID0 selected'
      )
    ));
    

    In this case, null maps to a NULL (default) value in the database column foreignkey_id, and 0 to a row with key 0.

    Outside this particular usecase however, I tend to think DCoder's comment is authoritative here...

    0 讨论(0)
提交回复
热议问题