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?
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'] : '';
}
Just check $i
and use ternaries:
function getValue($root, $i = null)
{
return (isset($i) && isset($root[$i]['Hello'])) ? $root[$i]['Hello'] : '';
return (isset($root['Hello'])) ? $root['Hello'] : '';
}
You could probably nest the two ternaries above into one return
but I would advise against it.
Along the lines of your current code:
function getValue($root, $i = null)
{
if(isset($i) && isset($root[$i]['Hello']))
{
return $root[$i]['Hello'];
}
elseif(isset($root['Hello']))
{
return $root['Hello'];
}
else
{
return '';
}
}