Write a function.

A

Anonymous

Guest
Hello everyone. I'm a self learner that is very new to programming.

Write a function(use native php) that accepts an array of opening or closing tags (for example, “<a>”, “</td>”) at the input, and returns the result of the correctness check: i.e. whether the sequence of tags accepted by the function is the structure of a valid HTML document. For example, the sequence “<a>”, “<div>”, “</div>”, “</a>”, “<span>”, “</span>” is the correct structure, and the sequence “<a > ”,“ <div> ”,” </a> ”- incorrect structure.
 
Your other two questions were specific enough to just need a single trick to solve; this one is a lot more open ended though. If you're just getting started you might want to look at something simpler.
 
That's what I did:

Code:
<?php

function checkTag($tag)
{

    $arr = [];

    $startTag = ['<html>', '<head>', '<body>'];

    $pairsTag = ['<html></html>', '<head></head>', '<body></body>'];


    foreach ($tag as $value) {
        $curr = $value;

        if (in_array($curr, $startTag)) {
            array_push($arr, $curr);
        } else {
            $prev = array_pop($arr);

            $pair = "{$prev}{$curr}";

            if (!in_array($pair, $pairsTag)) {
                return false;
            }
        }
    }


    return count($arr) === 0;
}

var_dump(checkTag(['<head></head>', '<body></body>'])); // true
 
Back
Top