php - Function for creating/adding dom element not quite right 2

one text

My last one was closed before I had an answer. One of the answers was saying that I had a typo with a ternary expression. The problem is the example code that was provided seemed to just slightly alter my code's spacing. I didn't see any true corrections. The suggestion that I use "null coalescing operator" instead of ternary expressions was good though. Here's my current code.

The problem is, instead of having an element wrap another, the child ends up next to the target instead of wrapped.

function newElement(array $element, array $parent=null) {
    $doc = $parent['doc'] ?? new DOMDocument;
    $node = $doc->appendChild($doc->createElement($element['tag'],$element['text']??null));
    if(isset($parent)){
        $parent['node']->appendChild($node);
    } else {
        $doc->appendChild($node);
    }
    if(isset($element['attr'])){
        foreach ($element['attr'] as $key => $value) {
            $node->setAttribute($key, $value);
        }
    }
    return ([
        'doc'=>$doc,
        'node'=>$parent['node']??$node,
        'html'=>htmlspecialchars_decode($doc->saveHTML())
    ]);
}

Here's some basic code that can be used to use the function

$element = newElement(['tag' => 'h4','attr'=>['class'=>"test"],'text'=>"Blah"]);
$element2 = newElement(['tag' => 'h4','text'=>"Blah2"],$element);
echo $element2['html'];

Source