Skip to content

Instantly share code, notes, and snippets.

@pl38
Last active December 6, 2021 12:26
Show Gist options
  • Select an option

  • Save pl38/02a4b83b780cd086a015a13c8baf6dfa to your computer and use it in GitHub Desktop.

Select an option

Save pl38/02a4b83b780cd086a015a13c8baf6dfa to your computer and use it in GitHub Desktop.

Script to switch PHP versions using Homebrew

Install grep via Homebrew to prefixing with g

 brew install grep
==> Caveats
All commands have been installed with the prefix "g".
If you need to use these commands with their normal names, you
can add a "gnubin" directory to your PATH from your bashrc like:
  PATH="/usr/local/opt/grep/libexec/gnubin:$PATH"

Add script to ~/.zshrc

installedPhpVersions=($(brew ls --versions | ggrep -E 'php(@.*)?\s' | ggrep -oP '(?<=\s)\d\.\d' | uniq | sort))

for phpVersion in ${installedPhpVersions[*]}; do
    value="{"

    for otherPhpVersion in ${installedPhpVersions[*]}; do
        if [ "${otherPhpVersion}" != "${phpVersion}" ]; then
            value="${value} brew unlink php@${otherPhpVersion};"
        fi
    done

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

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

Once the script is in ~/.zshrc run

$ alias | grep php

This will output something like below for every brew installed version of php:

7.3='{ brew unlink php@7.4; brew unlink php@8.0; brew unlink php@8.1; brew unlink php@8.1; brew link php@7.3 --force --overwrite; } &> /dev/null && php -v'
7.4='{ brew unlink php@7.3; brew unlink php@8.0; brew unlink php@8.1; brew unlink php@8.1; brew link php@7.4 --force --overwrite; } &> /dev/null && php -v'
8.0='{ brew unlink php@7.3; brew unlink php@7.4; brew unlink php@8.1; brew unlink php@8.1; brew link php@8.0 --force --overwrite; } &> /dev/null && php -v'
8.1='{ 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'

Add to the alias file or ~/.zshrc

# +---------+
# |   PHP   |
# +---------+

alias 7.3='{ brew unlink php@7.4; brew unlink php@8.0; brew unlink php@8.1; brew unlink php@8.1; brew link php@7.3 --force --overwrite; } &> /dev/null && php -v'
alias 7.4='{ brew unlink php@7.3; brew unlink php@8.0; brew unlink php@8.1; brew unlink php@8.1; brew link php@7.4 --force --overwrite; } &> /dev/null && php -v'
alias 8.0='{ brew unlink php@7.3; brew unlink php@7.4; brew unlink php@8.1; brew unlink php@8.1; brew link php@8.0 --force --overwrite; } &> /dev/null && php -v'
alias 8.1='{ 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'

and to switch run

$ 8.0

Then I comment out the script to stop issues with PowerLine etc. when a new version of PHP comes up I run through the process again.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment