Skip to content

Instantly share code, notes, and snippets.

@aslamdoctor
Created May 4, 2024 14:35
Show Gist options
  • Save aslamdoctor/b9620dab33eaf8a96fbaa4635b1e9ffd to your computer and use it in GitHub Desktop.
Save aslamdoctor/b9620dab33eaf8a96fbaa4635b1e9ffd to your computer and use it in GitHub Desktop.
Switch PHP version on Mac using Brew
  1. Check if grep is installed

grep --version

If it returns below

grep (BSD grep, GNU compatible) 2.6.0-FreeBSD

  1. Then install it using brew

brew install grep

  1. Add below shell script to ~/.zshrc
# 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

        value="${value} brew unlink php@${otherPhpVersion};"
    done

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

    alias "${phpVersion}"="${value}"
done
  1. Re-compile ~/.zshrc file

source ~/.zshrc

  1. Run commands like this to switch to specific version

e.g. 8.2

should return as below

PHP 8.2.1 (cli) (built: Jan 12 2023 03:48:24) (NTS)
Copyright (c) The PHP Group
Zend Engine v4.2.1, Copyright (c) Zend Technologies
    with Zend OPcache v8.2.1, Copyright (c), by Zend Technologies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment