Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
241 views
in Technique[技术] by (71.8m points)

What is the PHP shorthand for: print var if var exist

We've all encountered it before, needing to print a variable in an input field but not knowing for sure whether the var is set, like this. Basically this is to avoid an e_warning.

<input value='<?php if(isset($var)){print($var);}; ?>'>

How can I write this shorter? I'm okay introducing a new function like this:

<input value='<?php printvar('myvar'); ?>'>

But I don't succeed in writing the printvar() function.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For PHP >= 5.x:

My recommendation would be to create a issetor function:

function issetor(&$var, $default = false) {
    return isset($var) ? $var : $default;
}

This takes a variable as argument and returns it, if it exists, or a default value, if it doesn't. Now you can do:

echo issetor($myVar);

But also use it in other cases:

$user = issetor($_GET['user'], 'guest');

For PHP >= 7.0:

As of PHP 7 you can use the null-coalesce operator:

$user = $_GET['user'] ?? 'guest';

Or in your usage:

<?= $myVar ?? '' ?>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...