我可以将一个值分配给另一个我不知道是否存在于一行中的 var 吗?

Can I assign a value to a var from another which I don't know if exist in one row?

我正在寻找一种更好、更简单的方法来做到这一点。我记得我在某处看到了一个shorthand。

if (isset($user['passport'])) $passport=$user['passport'];

Edited to let you know what I mean

经典ASP:

user=request.form("user")
response.write user

ASP 不关心用户是否存在,所以 不打印任何内容

同PHP

$user=$_POST['user'];
echo $user;

PHP 打印注意:未定义变量

$passport=$user['passport']?$user['passport']:"Value if not set";

试试这个:

$passport = ($user['passport'])?: '';

如果您需要 shorthand 条件,您可以使用 ternary operator 作为:

$passport = (isset($user['passport']) ? $user['passport'] : '');

您可以使用 PHP 三元运算符来实现此目的

Link 了解三元运算符 http://php.net/manual/en/language.operators.comparison.php

示例php代码

<?php
// Example usage for: Ternary Operator
$passport = (isset($user['passport'])) ? $user['passport'] : '';

// The above is identical to this if/else statement
if (isset($user['passport'])) {
    $passport = $user['passport'];
} else {
    $passport = '';
}
?>

经典 ASP“可能不在乎”,但不要被显然 none 存在的值所愚弄。有时它们确实包含一些东西,例如Nothing。当然,这一切都取决于价值的原始来源。

我倾向于用来强制特定类型的变体的一种快速而肮脏的方法是在开头附加一个空字符串,例如:

user = "" & Request.Form("user")
'As a numeric example from a different source...
count = CInt("0" & rs("record_count"))

对于PHP你可以考虑:

$passport = "" . $user[passport];

(不幸的是,我对 PHP 了解不多。)