简体   繁体   English

PHP-如果未设置变量,则获取post变量

[英]PHP - If variable is not set, get post variable

I am trying to pass through a variable to a new name if it is set, or get a POST variable if the first variable is not set. 我正在尝试将变量设置为新名称,如果未设置第一个变量,则尝试获取POST变量。

This is my code but it is not working: 这是我的代码,但是不起作用:

if (isset($randombg)) {
    $background = $randombg;    
} else {  
   $background = $_POST['bg']) 
};

What is wrong with it, or how can I fix this? 它有什么问题,或者我该如何解决?

You have typos in your code. 您的代码中有错别字。 There is a ) in $background = $_POST['bg']) and a semicolon 有一个)$background = $_POST['bg'])和分号

you this should work: 您这应该工作:

$defaultbg = '#FFFFFF';

if (isset($randombg)) {
    $background = $randombg;    
} elseif( isset( $_POST['bg'] ) ) {  
   $background = $_POST['bg'];
   }else{
       $background = $defaultbg;
       }

[Feature] PHP 7.0.x + [功能] PHP 7.0.x +

If you are using PHP 7.0.x+ you can use following syntax: 如果您使用的是PHP 7.0.x +,则可以使用以下语法:

$background = $randombg ?? $_POST['bg'];

In this case $background will get value from first variable which is set and is not null. 在这种情况下, $background将从设置的第一个变量中获取值,并且该变量不为null。

You can do even something like this: 您甚至可以执行以下操作:

$background = $randombg ?? $_POST['bg'] ?? 'No background given'; 
// if $randombg and $_POST['bg'] will be not set or null $background will become 'No background given'

More about that feature you can read in PHP RFC: Null Coalesce Operator and PHP: New Features 有关该功能的更多信息,请参见PHP RFC:Null Coalesce OperatorPHP:新功能

About your code 关于您的代码

You have syntax in your code. 您的代码中有语法。 More informations below: 以下是更多信息:

if (isset($randombg)) {
    $background = $randombg;    
} else {  
   $background = $_POST['bg']) // you have syntax here, delete )
}

You can also use short syntax: 您还可以使用简短的语法:

$background = (isset($randombg)) ? $randombg : $_POST['bg'];

And it works as follows: 它的工作方式如下:

$background = (condition) ? 'when true' : 'when false';

More about it you can read here (Shorthand if/else) 关于它的更多信息,您可以在这里阅读(如果/否则为简写)

Mauybe $randombg is null or empty (that does not exactly means that is not set). Mauybe $ randombg为null或为空(这并不完全意味着未设置)。

Try this: 尝试这个:

if ($randombg) {
    $background = $randombg;    
} else {  
    $background = $_POST['bg'];
}

Or a shorten syntax: 或更简短的语法:

$background = null == $randombg
    ? $_POST['bg']
    : $randombg;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM