The code in this script lets you specify the domains you’re using, then simply returns the file path at the end.
This is a simple, low overhead way of creating a hreflang tag for PHP sites. I specifically used this for WordPress, adding it in the header template.