Possibly undefined argument for PHP function

When displaying values ​​obtained from a database, values ​​that may or may not exist, there is a lot of this in my PHP code:

if ( isset( $data['a'] ) )
    $a = number_format( $data['a'] );
else
    $a = '–';
if ( isset( $data['b'] ) )
    $b = number_format( $data['b'] );
else
    $b = '–';

(Simplified, for example, $data['a']are actually such things as $data[$date][$part]['errors']). This follows later <td><?= $a ?></td>and <td><?= $b ?></td>.

Using ?:instead ifmakes the code vertically more compact, but more ugly. I would like to add this to a function in order to have

$a = someFunction( $data['a'] );
$b = someFunction( $data['b'] );

which is much better. But the presence of the unset variable as an argument to the function raises two warnings: one for the unset variable, and then the other for the missing function argument. If I make an obvious function and call it with @...

function formatIfAvail( $num, $dec = 0 )
{
    if ( isset( $num ) )
        return number_format( $num, $dec );
    return '–';
}

....

$a = @formatIfAvail( $data['a'] );

... , . - @? PHP ++, #define - ...

#define NUMFMT( n, d )    ( isset( n ) ? number_format( n, d ) : '–' )

....

$a = NUMFMT( $data['a'], 0 );

... , , .

+4
1

PHP . , , () .

, , $data['a'] $data[$date][$part]['errors'], , - . " ", ArrayAccess ( ), .

, :

error_reporting(E_ALL & ~(E_NOTICE | E_WARNING));

, , , /. , @( ). :

$myValue = @$data['a'];
$myValue = @$data[$date][$part]['errors'];

.

, :

$myValue = @$data['a'] or $anotherValue;

PHP elvis ( ):

$myValue = @$data['a'] ?: $anotherValue;

or (||) .

, : "" . , , , . PHP ( , ).

, , . :

function someFunction( $num, $dec = 0 )
{
    return ($number !== null) ? number_format( $num, $dec ) : '-';
}
$myVal = someFunction(@data['a'] ?: null);
0

All Articles