W3docs

How to write a link like <a> which link to the same page in PHP?

In PHP, you can use the echo function to output an HTML <a> tag with a "#id" value for the href attribute, which will link to the same page.

In PHP, you can use the echo function to output an HTML <a> tag with a #id value for the href attribute, which will link to the same page. For example:

Example of using the "echo" function in PHP to output an anchor HTML tag

echo '<a href="#id">Link to same page</a>';

This outputs an HTML link that, when clicked, navigates to the element with the matching id on the same page.

Example of an HTML link and target element

<a href="#id">Link to same page</a>
<div id="id">Target content</div>

<div class="alert alert-info flex not-prose">Watch a course <span class="hidden md:block">Watch a video course</span> Learn object oriented PHP </div>

You can then use JavaScript to scroll the page to the id.

Example of using JavaScript to scroll the page to the id of a section

<script>
    document.querySelector('a[href="#id"]').addEventListener('click', function(event) {
        event.preventDefault();
        document.getElementById('id').scrollIntoView({
            behavior: 'smooth'
        });
    });
</script>

This will scroll the page smoothly to the element with the matching id.

Note on CSS smooth scrolling: Modern browsers support native smooth scrolling via CSS. Add scroll-behavior: smooth; echo <a> #id href element to achieve the same effect without JavaScript.