在PHP三元和空合并运算符中省略“else” - php

Improve this question

我正在阅读有关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' => '[email protected]'
];

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' => '[email protected]'
];

$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);,您会注意到由于the return value of $another_array[0]['occupation'] => true

将字符串放在数组中的每个数组之间-PHP - php

可以说我有一个包含9个句子的文本文件(可能更多!这只是一个例子),然后我在php中读取该文件并将其每3个句子拆分一次,并将其存储在变量中,从而导致该数组:$table = array( array( 'text number 1', 'text number 2', 'text number 3' …

PHP strtotime困境 - php

有人可以解释为什么这在我的服务器上输出为true吗?date_default_timezone_set('Europe/Bucharest'); var_dump( strtotime('29.03.2015 03:00', time()) === strtotime('29.03.2015 04:00�…

PHP-全局变量的性能和内存问题 - php

假设情况:我在php中运行一个复杂的站点,并且我使用了很多全局变量。我可以将变量存储在现有的全局范围内,例如$_REQUEST['userInfo'],$_REQUEST['foo']和$_REQUEST['bar']等,然后将许多不同的内容放入请求范围内(这将是适当的用法,因为这些数据指的是要求自…

php-casperjs获取内部文本 - php

我正在为casperjs使用php包装器-https://github.com/alwex/php-casperjs我正在网上自动化一些重复的工作,我需要访问一个项目的innerText,但是我尚不清楚如何从casperjs浏览器访问dom。我认为在js中我会var arr = document.querySelector('label.input…

PHP-从最后一个循环中删除逗号 - php

我在循环时有一个PHP,如果是最后一个循环,我想从,中删除​​最后一个逗号echo '],'; while($ltr = mysql_fetch_array($lt)){ echo '['; echo $ltr['days']. ' ,'. $ltr['name…