How can PHP code be optimized to efficiently handle external links in navigation menus?

To efficiently handle external links in navigation menus, PHP code can be optimized by checking if a link is external and adding the appropriate attributes, such as target="_blank" to open the link in a new tab. This helps improve user experience and ensures that external links are clearly identified to users.

function display_menu_item($url, $label) {
    if (strpos($url, 'http') === 0) {
        echo '<a href="' . $url . '" target="_blank">' . $label . '</a>';
    } else {
        echo '<a href="' . $url . '">' . $label . '</a>';
    }
}

// Example usage
display_menu_item('http://example.com', 'External Link');
display_menu_item('internal-page.php', 'Internal Link');