views:

24

answers:

1

Currently I have:

$content =  ($propXml->xpath('//content/section[@name="accommodations"]/content'));
$content = is_array($content) && (count($content)>0)?(string)$content[0]:false;
echo $content;

Is there a more succinct way of doing this? It would be shorter if PHP had the ability to automatically access an assigned array, but I have to reassign and check for the length...

A: 

There are many ways to make that shorter but it all depends on what you're doing in your script. I'm not shocked by that operation taking 3 lines of code but anyway, here are a few ideas that can make your code shorter, sometimes at the price of decreased readability:

  • Use empty()

    $content = (!empty($content)) ? (string) $content[0] : false;
    
  • Echo the node directly: (it automatically gets cast as a string)

    echo (!empty($content)) ? $content[0] : '';
    
  • Use array_shift() to get the first element of an array. (attention, it does modify the array. If it was the last element, you could use end() instead)

    echo array_shift($propXml->xpath('//content/section[@name="accommodations"]/content'));
    
Josh Davis
this is better than my isset($content[0]) variant. Haven't thought of empty...
nikic