Switching between PHP versions when using Homebrew

Homebrew, the popular package manager for macOS, allows you to install more than one version of PHP.

Now, let us assume you have installed PHP 7.4 and PHP 8.1 with HomeBrew. If you want to switch from PHP 7.4 to PHP 8.1, you need to run the following commands:

brew unlink php@7.4

and

brew link php@8.1 --force --overwrite

How about this instead?

8.1

The following shell script (added to ~/.bashrc or ~/.zshrc, whichever shell you prefer) creates aliases for every single PHP version you have installed with Homebrew:

# determine versions of PHP installed with HomeBrew
installedPhpVersions=($(brew ls --versions | ggrep -E 'php(@.*)?\s' | ggrep -oP '(?<=\s)\d\.\d' | uniq | sort))

# create alias for every version of PHP installed with HomeBrew
for phpVersion in ${installedPhpVersions[*]}; do
    value="{"

    for otherPhpVersion in ${installedPhpVersions[*]}; do
        if [ "${otherPhpVersion}" == "${phpVersion}" ]; then
            continue
        fi

        # unlink other PHP version
        value="${value} brew unlink php@${otherPhpVersion};"
    done

    # link desired PHP version
    value="${value} brew link php@${phpVersion} --force --overwrite; } &> /dev/null && php -v"

    alias "${phpVersion}"="${value}"
done

💡 macOS ships with grep, but that version does not support Perl-compatible regular expressions (PCREs) as used above.

Run

brew install grep

to install the latest version of grep. Homebrew installs grep wit the prefix g, hence ggrep.

With this script in place, when I open a new terminal and run

alias | grep php

I can see that the script created aliases as expected.

7.2='{ brew unlink php@7.3; brew unlink php@7.4; brew unlink php@8.0; brew unlink php@8.1; brew link php@7.2 --force --overwrite; } &> /dev/null && php -v'
7.3='{ brew unlink php@7.2; brew unlink php@7.4; brew unlink php@8.0; brew unlink php@8.1; brew link php@7.3 --force --overwrite; } &> /dev/null && php -v'
7.4='{ brew unlink php@7.2; brew unlink php@7.3; brew unlink php@8.0; brew unlink php@8.1; brew link php@7.4 --force --overwrite; } &> /dev/null && php -v'
8.0='{ brew unlink php@7.2; brew unlink php@7.3; brew unlink php@7.4; brew unlink php@8.1; brew link php@8.0 --force --overwrite; } &> /dev/null && php -v'
8.1='{ brew unlink php@7.2; brew unlink php@7.3; brew unlink php@7.4; brew unlink php@8.0; brew link php@8.1 --force --overwrite; } &> /dev/null && php -v'

To switch from any version of PHP to PHP 8.1, I now only need to run

8.1

I hope it helps!

What do you think?

Get in touch!