如果 meta 没有值 / 为空,则输出 0 的最短方法


Shortest way to output 0 if meta does not have value / is empty

>希望标题有意义,如果它们为空,我想输出0

我目前正在用这个输出值:

<?php meta('some-field'); ?>

编辑:上面的代码将回显出该值

例如,使用三元运算符。在 PHP 5.3 之后:

echo meta('some-field') ? : 0;

在 PHP 5.3 之前:

echo meta('some-field') ? meta('some-field') : 0;

假设meta()写入并且不返回任何内容...

function callback($buffer) {
    // check if buffer is empty, else return 0
    return (!empty($buffer)) ? $buffer : 0;
}
// turn output buffering on. the output is stored in an internal buffer. 
// The callback function will be called when the output buffer is flushed
ob_start('callback');
meta('some-field');
// Flush the output buffer
ob_end_flush();

工作示例:http://phpfiddle.org/main/code/42rr-zh8j


假设meta()返回值并且不写入任何内容...

// Check if meta return value is empty, print meta value else print 0
echo ( !empty(meta('some-field')) ) ? meta('some-field') : 0;

您可以将meta()包装在您自己的自定义函数中:

function myMeta($key, $default = '0') {
   $meta = meta($key);
   return empty($meta) ? $default : $meta;
}

并使用它代替元:

myMeta('some-field');
myMeta('some-field', 'other-default-value');