I am working on various PHP-based projects that have different version requirements, for both work and side projects. Homebrew is actually great for this as it allows you to install more than one version of PHP on MacOS. You can then to switch the PHP version easily via brew unlink and brew link but over time, this can become tedious.

Quick note: We can use shivammathur/homebrew-php to install any PHP older than 8.0.

So naturally, we can create a utility function to do this. Bonus points:

  • It checks against installed PHP version (defined manually in the installed_php_versions array).
  • It skips switching if the version we want to switch is already active.

Put this in the .zshrc file and reload your terminal, and we are good to go. To use this, simply run switchphp <php_version> for example switchphp 8.2.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
switchphp() {
    installed_php_versions=("7.4" "8.0" "8.1" "8.2" "8.3")
    current_php_version=$(php -v | grep -o 'PHP [0-9]*\.[0-9]*' | cut -d ' ' -f 2 | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')
    target_php_version=$1
    
    if [ -z "$1" ]; then
        echo "No PHP version provided"
        return 1
    fi
    
    if [[ ! ${installed_php_versions[(r)$target_php_version]} ]]; then
        echo "Invalid PHP version provided"
        return 1
    fi
    
    if [[ $target_php_version == $current_php_version ]]; then
        echo "You are already on PHP version $1"
        return 1
    fi
    
    brew unlink php@"$current_php_version"
    brew link php@"$target_php_version"
    php -v
}

Hope this is useful!