Reputation: 387
I'm newbie to PHP and I have a simple question.
UPDATE: I am using PHP 5.6 (Best solution would be to update the PHP version but let's suppose that I can only use PHP 5.6)
I have a code like below:
function findOrCreateMasterRecord ($masterTableName, $masterName) {
if (isset($sampleArr[$masterTableName][$masterName])) {
return $sampleArr[$masterTableName][$masterName];
}
return getNewMasterIndex($masterTableName, $masterName);
}
This code works properly. But I want to make "if" block more simple because it approaches twice to same index($sampleArr[$masterTableName][$masterName]) and I think this is...somewhat..not good.
Is there a way to make this function to be more effective?
Thank you.
Upvotes: 0
Views: 58
Reputation: 7609
In PHP 7+ you could use the null coalescing operator: ??
function findOrCreateMasterRecord ($masterTableName, $masterName)
{
return $sampleArr[$masterTableName][$masterName] ?? getNewMasterIndex($masterTableName, $masterName);
}
If not in PHP 7, a ternary operator could shorten your code but will still be redundant:
function findOrCreateMasterRecord ($masterTableName, $masterName)
{
return isset($sampleArr[$masterTableName][$masterName]) ? $sampleArr[$masterTableName][$masterName] : getNewMasterIndex($masterTableName, $masterName);
}
With shorter variable names for a better read:
// 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);
}
Upvotes: 3
Reputation: 7485
You can reduce to the following, as your condition will never be met:
<?php
function findOrCreateMasterRecord ($masterTableName, $masterName) {
return getNewMasterIndex($masterTableName, $masterName);
}
Upvotes: 0