如果为空,如何添加默认值?
I have the following code:
<input class="mt upbb" type="text" name="your_name" id="your_name" value="<?php echo info_username_get_meta( 'your_name' ); ?>">
How can I add a default text to that if the value is empty? Thanks in advance!
You can always use a ternary operator if you want to do things inline:
value="<?php echo (!empty(info_username_get_meta( 'your_name' )) ? info_username_get_meta( 'your_name' ) : 'DEFAULT NAME' ; ?>"
Or break it out and assign the name in the code above:
<?php
$name = (!empty(info_username_get_meta( 'your_name' )) ? info_username_get_meta( 'your_name' ) : 'DEFAULT NAME';
?>
<input class="mt upbb" type="text" name="your_name" id="your_name" value="<?php echo $name; ?>">
I'm gonna expand on the above answer and throw in a short php way to do it:
value="<?= info_username_get_meta( 'your_name' ) ?? 'DEFAULT NAME'; ?>"
<?= ?>
is a replacement for <?php echo '' ?>
??
is a replacement for ternary operators, basically if the first one has data it's used otherwise it prints the second one.
If you're using php 7+ you can do this:
<input class="mt upbb" type="text" name="your_name" id="your_name" value="<?php echo (info_username_get_meta( 'your_name' ) ?? '') ?>">
Otherwise you can use:
<input class="mt upbb" type="text" name="your_name" id="your_name" value="<?php echo (!empty($value = info_username_get_meta( 'your_name' )) ? $value : '') ?>">
If the info_username_get_meta
function is yours, you could modify it to take the default value as a second parameter and return that if it doesn't find anything for the first parameter
function info_username_get_meta($username, $default)
{
$meta = // whatever happens with $username to get meta
return $meta ?: $default;
}
I think that would make the presentation code a bit cleaner.
If you don't have access to that function you can use this expression
<?php echo info_username_get_meta( 'your_name' ) ?: 'default value'; ?>
The ?:
operator is a shortened ternary operator. It evaluates to the left side value unless it is falsey, in which case it uses the right side value. This shortened version of the ternary is available since PHP 5.3.
The null coalescing operator (??
) will also work if the "empty" value your function returns is null
. It specifically addresses null values, so it won't work on empty strings or other falsey values.