【问题标题】:How can I use my variable only if it is defined? [duplicate]只有定义了变量,我如何才能使用它? [复制]
【发布时间】:2019-04-18 08:27:25
【问题描述】:
我喜欢使用form[fieldsdata],只有当它被定义时:
$fieldsJson = $data["form[fieldsdata]"] ? $data["form[fieldsdata]"] : "";
但错误信息仍然是:
注意:未定义索引:form[fieldsdata]
【问题讨论】:
标签:
php
variables
undefined
defined
【解决方案1】:
您可以使用 isset() 检查它是否已定义,或者(如果您使用的是 PHP 7)使用空合并运算符 (??)
使用 isset
$fieldsJson = isset($data["form[fieldsdata]"]) ? $data["form[fieldsdata]"] : "";
使用空合并运算符(仅限 PHP 7)
$fieldsJson = $data["form[fieldsdata]"] ?? "";
请注意,如果索引存在但具有null 值,则使用空合并也会应用空字符串值。
【解决方案2】:
使用
$fieldsJson = isset($data["form[fieldsdata]"]) ? $data["form[fieldsdata]"] : "";
【解决方案3】:
// Declare an array
$array = array();
// Use isset function
echo isset($array['geeks']) ? 'array is set.' : 'array is not set.';
输出:
array is not set.