Magento 2 – Check if Attribute Has Value

attributesmagento-2.1magento2PHPproduct

I try to display two custom attributes in the product view page but this attributes is not exist for all products. How I can check if current product contain one of this two attributes?

I use this code to get the attributes value:

<?php /* @escapeNotVerified */ echo $_product->getResource()->getAttribute('data_sheet')->getFrontend()->getValue($_product); ?>
<?php /* @escapeNotVerified */ echo $_product->getResource()->getAttribute('health_sheet')->getFrontend()->getValue($_product); ?>

Best Answer

Try this

<?php 
    $dataSheet = $this->helper('Magento\Catalog\Helper\Output')->productAttribute($_product, $_product->getDataSheet(), 'data_sheet'); 
    $healthSheet = $this->helper('Magento\Catalog\Helper\Output')->productAttribute($_product, $_product->getHealthSheet(), 'health_sheet'); 
    if(isset($dataSheet) || isset($healthSheet)){
        //display your DIV
    }
?>