Robert Robert - 1 month ago 5
PHP Question

Not writing excessive amounts of code

So, I have this function that I am trying to run that looks like this:

function getValue($root, $i = null)
{
if(isset($root[$i]['Hello'])
{
return $root[$i]['Hello'];
}
elseif(isset($root['Hello'])
{
return $root['Hello'];
}
else
{
return '';
}
}


I do not want
[$i]
to be there if it is null. How could I go about doing this without writing a lot of code that is basically repetitive?

Answer

Something along the lines of

function getValue($root, $i = null)
{
    return $i ? isset($root[$i]) : isset($root);
}

if I understand what you're trying to achieve correctly.

With the question updated I think the shortest you can get away with is this:

function getValue($root, $i = null)
{
    $_t = isset($root[$i]) ? $root[$i] : $root;
    return isset($_t['Hello']) ? $_t['Hello'] : '';
}

https://3v4l.org/ZKtQi

Comments