Fetching field values only if they exist and applying them automatically as entity labels I have a content type with these fields, among others:


field_address – required
field_entrance – not required
field_apartment_number – not required (or actually required if a previous field meets a certain criteria, otherwise not shown at all)


With the Automatic Entity Label modul I can use tokens to save the node title using this pattern:

[node:field_address] [node:field_entrence] [node:field_apartment_number]

If any of the non required fields are left blank there's no value from those fields saved to the node title. However, the whitespace between the tokens is still saved, and I don't want that. I'm not good at PHP but this I what I have, copy-pasted from various sources:

&lt;?php

$address = field_get_items('node', $node, 'field_address');
$entrance = field_get_items('node', $node, 'field_entrence');
$apartment_number = field_get_items('node', $node, 'field_apartment_number');

print $address['value'];

if ($entrance) {
   print ' ' . $entrance['value'];
}

if ($apartment_number) {
   print ' ' . $apartment_number['value'];
}

?&gt;


But it doesn't work. Instead, no title is saved at all. How do I correct my code?
As far as I remember, field_get_items() returns an array of items. 
In your case something like:

    if (count($address)) {
       print $address[0]['value'];

       if (count($entrance)) {
          print ' ' . $entrance[0]['value'];
       }

      if (count($apartment_number)) {
         print ' ' . $apartment_number[0]['value'];
      }
   }


should work.