数组中的if语句

时间:2019-02-27 10:10:10

标签: php arrays if-statement

我有一个使用cURL发布的数据。现在我想知道是否可以为1个数组传递2个变量。

这是即时通讯用于发送数据的代码

$data = [
    'completion_date'       =>  '31/03/2019',
    'customer_id'           =>  80,
    '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'        =>  'Customer notes',
    'job_products'          =>  json_encode($job_products)
];

现在我想知道我是否可以做这样的事情

'customer_notes'        =>  $variable1 or $variable2,

我要完成的工作是,如果$variable1为空,则使用$variable2中的数据,反之亦然。是否真的有办法做到?

'full_name'=> if $var1 empty use $var2

2 个答案:

答案 0 :(得分:5)

您可以使用三元运算符

'customer_notes' => !empty($variable1) ? $variable1 : $variable2,

答案 1 :(得分:1)

您可以使用任何一个人

'customer_notes' => !empty($variable1) ? $variable1 : $variable2,

'customer_notes' =>  $variable1 ?? $variable2, (PHP 7)