You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP cURL提交数组:如何实现数组元素双变量非空fallback逻辑?

实现数组元素的双变量 Fallback 逻辑(PHP)

当然可以实现!在PHP里,我们有两种非常简洁的方式来实现你要的「如果变量1为空就用变量2,否则用变量1」的逻辑,完全可以直接嵌入到你的数组定义里。

核心方案:用三元运算符或 Null 合并运算符

根据你对「为空」的定义不同,选择对应的写法:

  1. 三元运算符 ?::处理所有「假值」(空字符串、0、false、null 等)
    这个运算符的逻辑是:如果左侧表达式为「真」(非假值),就用左侧的值;否则用右侧的值。非常适合你需要把空字符串也替换掉的场景,比如 full_name 字段。

  2. Null 合并运算符 ??:仅处理 null 或未定义的变量
    如果你只想在变量1是null(或者根本没定义)的时候才用变量2,空字符串、0这些合法值保留,就用这个运算符。

修改后的代码示例

把你的数组里需要设置逻辑的字段替换成下面的写法就行:

// 假设你已经定义了对应的 fallback 变量,比如 $default_full_name、$default_customer_notes
$data = [
    'completion_date' => '31/03/2019',
    'customer_id' => 80,
    // 如果 $full_name 非空(非假值)就用它,否则用 $default_full_name
    'full_name' => $full_name ?: $default_full_name,
    'email_address' => 'email@email.com',
    'telephone' => '012122212',
    'mobile' => '0787878',
    'address' => 'Line 1 address'.chr(10).'Line 2 address',
    'city' => 'City',
    'county' => 'County',
    'postcode' => 'Postcode',
    'site_company_name' => 'Site Company Name',
    'site_full_name' => 'Site Contact Name',
    'site_telephone' => '012121212',
    'site_mobile' => '07878787',
    'site_fax' => 'Depreciated, not in use',
    'site_email_address' => 'email@email.com',
    'site_address' => 'Site Line 1 address'.chr(10).'Line 2 address',
    'site_city' => 'Site City',
    'site_county' => 'Site County',
    'site_postcode' => 'Site Postcode',
    'site_notes' => 'Site Notes',
    'customer_ref' => $RecordID,
    'wo_ref' => 'Customer Job Ref',
    'po_ref' => $OrderID,
    'short_description' => 'short description of job',
    'description' => 'long description of job',
    // 如果 $customer_notes 不是 null 就用它,否则用 $default_customer_notes
    'customer_notes' => $customer_notes ?? $default_customer_notes,
    'job_products' => json_encode($job_products)
];

更精确的判断(可选)

如果你需要更严格的判断,比如只替换空字符串,不替换0或false,可以写完整的三元表达式:

'full_name' => ($full_name !== '') ? $full_name : $default_full_name,

这种写法完全适配你用cURL提交数据的场景,数组初始化时就能直接完成逻辑处理,不用额外写一堆if语句。

内容的提问来源于stack exchange,提问作者Marek Prymula

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:15:20