Виктор Лебедев Виктор Лебедев - 3 months ago 22
PHP Question

php refactoring small function

Is it possible to reduce this expression to one line?

echo '<li>';
echo $value['name'];
if ($value['childs']) {
echo '<ul>';
echo $this->arrayToString($value['childs']);
echo '</ul>';
}
echo '</li>';


For example:

echo '<li>' . $value['name'] // what to do if statement? ... ;

Answer

It deffinitely is possible:

echo '<li>' . $value['name'] . ($value['childs'] ? '<ul>' . $this->arrayToString($value['childs']) . '</ul>' : '') . '</li>';

But I really do not recommend it. I will be much less readable. Maybe reather try to extract one part to another function like this:

function printItem($value)
{
    echo '<li>' . $value['name'] . $this->printItemChilds($value) . '</li>';
}

function printItemChilds($value)
{
    return $value['childs'] ? '<ul>' . $this->arrayToString($value['childs']) . '</ul>' : '';
}