这段代码如何才能更短?

How can this code to be more shorter?

我是 PHP 的新手,我有一个简单的问题。

UPDATE:我正在使用 PHP 5.6(最佳解决方案是更新 PHP 版本,但假设我只能使用 PHP5.6)

我有如下代码:

function findOrCreateMasterRecord ($masterTableName, $masterName) {

    if (isset($sampleArr[$masterTableName][$masterName])) {
        return $sampleArr[$masterTableName][$masterName];
    }

    return getNewMasterIndex($masterTableName, $masterName);

}

这段代码工作正常。但我想让 "if" 块更简单,因为 它两次接近相同的索引 ($sampleArr[$masterTableName][$masterName]) 我认为这是......有点..不好.

有没有办法让这个功能更有效?

谢谢。

PHP 7+ 你可以使用 null coalescing operator: ??

function findOrCreateMasterRecord ($masterTableName, $masterName)
{
    return $sampleArr[$masterTableName][$masterName] ?? getNewMasterIndex($masterTableName, $masterName);
}

如果不在 PHP 7 中,ternary operator 可以缩短您的代码,但仍然是多余的:

function findOrCreateMasterRecord ($masterTableName, $masterName)
{
    return isset($sampleArr[$masterTableName][$masterName]) ? $sampleArr[$masterTableName][$masterName] : getNewMasterIndex($masterTableName, $masterName);
}

使用更短的变量名以便更好地阅读:

// PHP 7
function findOrCreateMasterRecord ($table, $name)
{
    return $arr[$table][$name] ?? getNewMasterIndex($table, $name);
}

// Under PHP 7
function findOrCreateMasterRecord ($table, $name)
{
    return isset($arr[$table][$name]) ? $arr[$table][$name] : getNewMasterIndex($table, $name);
}

您可以减少为以下内容,因为您的条件永远不会满足:

<?php
function findOrCreateMasterRecord ($masterTableName, $masterName) {
    return getNewMasterIndex($masterTableName, $masterName);
}