Check if an element is an array in PHP

Description

The following code shows how to check if an element is an array.

Example


/* w  w  w  .j  av  a 2s . co m*/
<?php
$xml = simplexml_load_file('test.xml');
?>
<html>
<head>
</head>

<body>
<?php
foreach ($xml->book as $book) {
  echo '<h2>' . $book->title . '</h2>';
  
  echo '<p class="author">';
  if (is_array($book->author)) {
    echo implode(', ', $book->author);
  } else {
    echo $book->author;
  }  
  echo '</p>';
                
  echo '<p class="publisher">' . $book->publisher . '</p>';
  echo '<p class="publisher">ISBN: ' . $book['isbn13'] . '</p>';
                  
  echo '<p>' . $book->description . '</p>';
}
?>
</body>
</html>

The following code is for test.xml.


<?xml version='1.0' encoding='utf-8'?>
<inventory>// w  w  w .  j  a v a  2  s .com
  <book isbn13='1'>
    <title>PHP</title>
  <author>Jack</author>
  <publisher>Publisher 1</publisher>
  <description>PHP Book</description>
  </book>
  <book isbn13='2'>
    <title>XML</title>
  <author>Jane</author>
  <publisher>Publisher 2</publisher>
  <description>XML Book</description>
  </book>
</inventory>

The code above generates the following result.





















Home »
  PHP Tutorial »
    XML »




DOM
SimpleXML
SimpleXMLElement
XML Parser