Install multiple versions of PHP on Ubuntu 22.04 (Jammy Jellyfish)

PHP is an excellent programming language that constantly evolves to bring us new features and improvements. This is why we will often need more than one version installed on our computer. The good news is that in Ubuntu we can easily swap PHP versions, today we will see how to make this possible.
Enable unsupported versions
The first step is to validate that we have the necessary dependencies. If you already have the default version installed, in this case 8, this step is not necessary.
sudo apt-get install software-properties-common
Next, you must add the PHP repositories. This step is necessary because not all versions are found in the repositories of the new versions of Ubuntu.
sudo LC_ALL=C.UTF-8 add-apt-repository ppa:ondrej/php
After adding the repositories, we update our list of packages.
sudo apt-get update -y
Install a new version of PHP
For this example, we are going to install version 7.4 of PHP. However, you should be able to install the version you require according to your needs.
sudo apt install php7.4
- Install PHP extensions in Ubuntu
Change between PHP versions
You must bear in mind that after installing a new version of PHP, it will not be automatically enabled. To change version, you must execute the following command:
sudo update-alternatives --config php
You must type the option you want according to the versions you have installed.
There are 2 choices for the alternative php (providing /usr/bin/php).
Selection Path Priority Status
------------------------------------------------------------
* 0 /usr/bin/php8.1 81 auto mode
1 /usr/bin/php7.4 74 manual mode
2 /usr/bin/php8.1 81 manual mode
Press to keep the current choice[*], or type selection number:
This will change the version of PHP that you run from the console. However, if you want to change the PHP version in Apache, you must execute the following commands according to your needs and installed versions.
sudo a2dismode php8.1
sudo a2enmod php7.4
After this, you must restart Apache.
sudo apachectl restart