Change PHP version on Mac with Brew


This post goes over how to change PHP version on macOS with Homebrew:

Prerequisites

Latest

Install the latest PHP version:

brew install php

Check the version:

php -v
PHP 8.2.1 (cli) (built: Jan 12 2023 02:29:10) (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

Version

Install PHP 7.4:

brew install [email protected]

If you get the error:

Error: [email protected] has been disabled because it is a versioned formula!

Then find an unsupported version of PHP from shivammathur/php:

brew search php

And install the version:

brew install shivammathur/php/[email protected]

Link the version:

If you get a symlink error, then unlink php:

brew unlink php

And link the version:

Update your PATH in ~/.zshrc:

echo 'export PATH="/opt/homebrew/opt/[email protected]/bin:$PATH"' >> ~/.zshrc
echo 'export PATH="/opt/homebrew/opt/[email protected]/sbin:$PATH"' >> ~/.zshrc
source ~/.zshrc

Or ~/.bashrc:

echo 'export PATH="/opt/homebrew/opt/[email protected]/bin:$PATH"' >> ~/.bashrc
echo 'export PATH="/opt/homebrew/opt/[email protected]/sbin:$PATH"' >> ~/.bashrc
source ~/.bashrc

Check the version:

php -v
PHP 7.4.33 (cli) (built: Jan 21 2023 06:43:54) ( NTS )
Copyright (c) The PHP Group
Zend Engine v3.4.0, Copyright (c) Zend Technologies
    with Zend OPcache v7.4.33, Copyright (c), by Zend Technologies

Revert

Change back to the latest PHP version:

brew unlink [email protected] && brew link php

Update your ~/.zshrc or ~/.bashrc:

-export PATH="/opt/homebrew/opt/[email protected]/bin:$PATH"
-export PATH="/opt/homebrew/opt/[email protected]/sbin:$PATH"
+export PATH="/opt/homebrew/opt/php/bin:$PATH"
+export PATH="/opt/homebrew/opt/php/sbin:$PATH"


Please support this site and join our Discord!