Changing PHP version with Valet and Homebrew (OSX)

Tom

November 13, 2020

Get homebrew / Get Valet

Recently, I updated the PHP on my machine to version 7.4 using homebrew for Mac OS only to then realise that one of my older projects that I still needed to maintain, made on version 7.2 would no longer work due to using depreciated PHP functions such as array_key_exists.

The long term solution to this would be to update the project so it’s compatible with PHP version 7.4, but for the sake of time, and potential fixes that needed to go out immediately, I needed to be able to develop this project in the environment it’s running in. Fortunately, I use valet to develop all my PHP applications a tool I can only recommend for PHP developers. Valet allows you to develop PHP applications on your local machine with a much higher level of ease than I’ve found using other services such as dockers or XAMP/MAMP.

Valet, with the use of homebrew, supports switching your system PHP version at will to any version installable via homebrew. So switching versions can be as simple as the following:

brew search php

This will show you all the versions of PHP available via brew, the “php” package represents the latest stable PHP version (which at the time of writing is 7.4) you can also see that versions 7.2 and 7.3 are available and I have them installed.
If you do not yet have the PHP version installed, you can install it by entering:

brew install php@7.2

Once installed, you can then use this with valet. By default, valet will use the system PHP version however you can override this by running:

valet use php@7.2

You should then see various outputs that look like the following:
Now you can check that your PHP version has changed:

php -v

You should see your PHP version has changed:


It’s as simple as that!

That’s how you can quickly and easily switch your PHP version using valet and homebrew. Your computer may need a reboot if the change does not seem to take affect, I have only encountered this once in my experience though.

So the only question that remains now is, how do I get back to where I was?

Reverting back to the latest PHP

Once you have finished developing, you’re likely going to want to return to the latest version of PHP for your modern/new applications. Doing this is as simple as downgrading, just tell valet to use “php”, which as we discovered earlier, is the latest version of PHP. So lets run that:

valet use php

As before, you should see an output like the following:


php -v

You should see your PHP version has reverted.

Tom

Tom

A Web, Tech, Football and Video Game enthusiast. Anything can be settled in smash! I’m a Software Engineer on the nerd.vision team with various front-end and back-end skills.