php - 省略 PHP 三元和空值合并运算符中的“else”
问题描述
我正在阅读并尝试使用 PHP 中的三元和空值合并运算符。
所以,而不是写
if (isset($array['array_key']))
{
$another_array[0]['another_array_key'] = $array['array_key'];
}
else
{
// Do some code here...
}
而不是使用空合并或三元运算符缩短它,我尝试使用空合并进一步缩短代码,但没有'else'部分,因为我并不真正需要。我搜索了它并发现了一些不是我想要的解决方案。
我试过了,两种解决方案都有效!
$another_array[0]['another_array_key'] = $array['array_key'] ??
$another_array[0]['another_array_key'] = $array['array_key'] ? :
print_r($another_array);
注意没有;在上面一行的末尾。
我的问题是:这是一段可以接受的代码吗?我认为可能很难用评论来解释它,因为一段时间后它可能会成为可读性的负担。
抱歉,如果这是一个类似的问题 - 我真的没有时间检查它们,因为 Stack Overflow 提出了很多建议。
这将是一个“完整”的代码示例:
<?php
$another_array = [];
$array = [
'name' => 'Ivan The Terrible',
'mobile' => '1234567890',
'email' => 'tester@test.com'
];
if (isset($array['name']))
{
$another_array[0]['full_name'] = $array['name'];
}
$another_array[0]['occupation'] = $array['occupation'] ??
// or $another_array[0]['occupation'] = $array['occupation'] ? :
print_r($another_array);
解决方案
可重复性、可维护性...如果您想测试许多可能的数组键,然后将它们添加或不添加到最终数组中,没有什么能阻止您创建第三个数组,该数组将保存键以检查和循环遍历它:
<?php
$another_array = [];
$array = [
'name' => 'Ivan The Terrible',
'mobile' => '1234567890',
'email' => 'tester@test.com'
];
$keysToCheck = [
// key_in_the_source_array => key_in_the_target
'name' => 'full_name',
'occupation' => 'occupation'
// if you want to test more keys, just add them there
];
foreach ($keysToCheck as $source => $target)
{
if (isset($array[$source]))
{
$another_array[0][$target] = $array[$source];
}
}
print_r($another_array);
请注意
$another_array[0]['occupation'] = $array['occupation'] ??
print_r($another_array);
被评估为
$another_array[0]['occupation'] = $array['occupation'] ?? print_r($another_array);
如果你在print_r($another_array);
之后添加另一个,你会注意到$another_array[0]['occupation'] => true
因为返回值print_r()
推荐阅读
- c# - 以下正则表达式的 Python 正则表达式
- datetime - 使用特定小时值更新日期时间变量
- three.js - three.js 矩阵乘法未按预期工作
- java - 从 SQLite 获取数据并显示到 RecyclerView
- android - 如何解决在android运行时找不到的BASE_MAP.fill(255)函数中的react-native?
- python - 将 TensorFlow 模型转换为冻结的 .pb 图
- java - 在类路径资源中定义名称为“entityManagerFactory”的 bean 创建错误 - SO 的解决方案不起作用
- cmd - 如何获取 Windows 批处理脚本
- html - CSS 通过表单的 id 摆脱列表点
- django - 为什么电子邮件是在本地发送而不是通过服务器发送的?