Search code examples
phpdrupal-8drupal-fields

Cannot get array element by key, but key exists on array


I'm working with Drupal 8, but since this looks like a PHP problem to me, I'm asking it here and not on Drupal Answers.

The isset statement in the following code should return TRUE, but it does not:

/*
$specifier = 'field_google_hire_identifier‎'
$field_storage_definitions = array of objects
*/

var_dump(
  isset($field_storage_definitions[$specifier]),
  $specifier,
  $field_storage_definitions[$specifier],
  $field_storage_definitions
);
die;

Output on the screen: var_dump() output Other array elements... var_dump() output Other array elements...

Original output HTML: https://codepen.io/anon/pen/ZwRJdR

Array keys:

var_dump( array_keys($field_storage_definitions));

Output on the screen: array keys

I'm kind of clueless why isset($field_storage_definitions[$specifier] is FALSE and $field_storage_definitions[$specifier] is NULL

I uninstalled APC and disabled Opcache.


Solution

  • There was a right to left mark at the end of the string that was used to select the array key. Since the string and the array key were not the same, the array key could not be retrieved.

    The left to right mark can be removed using

    preg_replace('/\p{C}+/u', "", $string)
    

    See https://stackoverflow.com/a/23131396/6653862

    You can check if a string contains invisible characters by using

    json_encode($string)