Nullsafe Operator
Learn about the nullsafe operator and how it provides the ability to handle the NULL data type.
The nullsafe operator is used in a chain of object property references. If one of the properties in the chain does not exist (in other words, it is considered NULL
), the operator returns a value of NULL
safely without issuing a warning.
In our example, we must have the following:
An Extended Markup Language (XML) file named
produce.xml
.Lines 4–15: We also need to define a
getQuantity()
function that first checks to see if that property is not empty before proceeding to the next level.Lines 18–30: A code snippet that scans through the XML document and displays quantities.
<?php // Define the getQuantity() function function getQuantity(SimpleXMLElement $xml, string $type, string $item) { $qty = 0; if (!empty($xml->dept)) { if (!empty($xml->dept->$type)) { if (!empty($xml->dept->$type->$item)) { $qty = $xml->dept->$type->$item; } } } return $qty; } // Load the XML file $xml = simplexml_load_file(__DIR__ . '/produce.xml'); // Define the produce array with types and items $produce = [ 'fruit' => ['apple','banana','cherry','pear'], 'vegetable' => ['artichoke','beans','cabbage','squash'] ]; $pattern = "%10s : %d\n"; // Pattern for displaying item and quantity // Iterate over each type of produce foreach ($produce as $type => $items) { echo ucfirst($type) . ":\n"; // Print the type (capitalized) // Iterate over each item in the produce type foreach ($items as $item) { $qty = getQuantity($xml, $type, $item); // Get the quantity for the item printf($pattern, $item, $qty); // Print the item and quantity using the pattern } } ?>
Displaying array elements with a combination of XML files using nested If statements in PHP 7
As we start dealing with deeper nesting levels, the function ...