Search code examples
phpconditional-operator

PHP - ternary for undefined index


I have a PHP error notice:

Undefined index: inventory_amount

$chains[$key] = intval($chain_product['inventory_amount']);

Is it possible to fix it in one line like with ternary function and not with:

if(!empty($chain_product['inventory_amount'])) {
     $chains[$key] = intval($chain_product['inventory_amount']);
}

New with PHP. Thanks


Solution

  • Yes, PHP has ternary operator.

    Like this:

    $variable = ( condition ? true : false );
    

    So in your case it like this:

    $chains[$key] = ( !empty($chain_product['inventory_amount']) ? intval($chain_product['inventory_amount']) : 0 );
    

    so if you have inventory_amount empty, it will have 0 assigned as a "fallback".