Checking empty object Is there a better method for covering errors in my case? I am looking for best practice for now and future instances.

Foreseen errors that could arise:


No attributes at all
Some attributes could be missing
Attribute value could be empty




// converting dom into array to use later
$fields = $dom-&gt;getElementsByTagName($field);
$arr['field'] = array();

foreach ($fields as $field) {
    $attributes = isset($field-&gt;attributes) ? $field-&gt;attributes : NULL;

    if (!empty($attributes)) {
        // the method getNamedItem($string) returns NULL if not found
        $name = !empty($attributes-&gt;getNamedItem('name')) ? $attributes-&gt;getNamedItem('name')-&gt;nodeValue : NULL;
        $id = !empty($attributes-&gt;getNamedItem('id')) ? $attributes-&gt;getNamedItem('id')-&gt;nodeValue : NULL;
        $field_name = !empty($attributes-&gt;getNamedItem('field_name')) ? $attributes-&gt;getNamedItem('field_name')-&gt;nodeValue : NULL;

        if (!empty($name) &amp;&amp; !empty($id) &amp;&amp; !empty($field_name)) {
            $arr['field'][$name][$id][$field_name] = $field-&gt;nodeValue;
        }
    }
}
I think it is cleaner to handle special cases early; your code winds up less indented.

// converting dom into array to use later
$fields = $dom-&gt;getElementsByTagName($field);
$arr['field'] = array();

foreach ($fields as $field) {
  $attributes = isset($field-&gt;attributes) ? $field-&gt;attributes : NULL;

  if (empty($attributes)) {
    continue;
  }

  $name = !empty($attributes-&gt;getNamedItem('name')) ? $attributes-&gt;getNamedItem('name')-&gt;nodeValue : NULL;
  $id = !empty($attributes-&gt;getNamedItem('id')) ? $attributes-&gt;getNamedItem('id')-&gt;nodeValue : NULL;
  $field_name = !empty($attributes-&gt;getNamedItem('field_name')) ? $attributes-&gt;getNamedItem('field_name')-&gt;nodeValue : NULL;

  if (empty($name) || empty($id) || empty($field_name)) {
    continue;
  }

  $arr['field'][$name][$id][$field_name] = $field-&gt;nodeValue;
}


This looks less complicated, at least to me, but it does exactly the same work.

You could also introduce a method to get the nodeValue or NULL, given $attributes and a name.

// converting dom into array to use later
$fields = $dom-&gt;getElementsByTagName($field);
$arr['field'] = array();

foreach ($fields as $field) {
  $attributes = isset($field-&gt;attributes) ? $field-&gt;attributes : NULL;

  if (empty($attributes)) {
    continue;
  }

  $name       = nodeIfPresent($attributes, 'name');
  $id         = nodeIfPresent($attributes, 'id');
  $field_name = nodeIfPresent($attributes, 'field_name');

  if (empty($name) || empty($id) || empty($field_name)) {
    continue;
  }

  $arr['field'][$name][$id][$field_name] = $field-&gt;nodeValue;
}