Installing PHP7.1 on Ubuntu 16.04

Step 1

sudo apt-get install software-properties-common
sudo add-apt-repository ppa:ondrej/php
sudo apt-get update

Note: There might be some errors as follows after running sudo apt-get update:

Reading package lists... Done
W: GPG error: xenial InRelease: The following signatures couldn't be verified because the public key is not available: NO_PUBKEY 4F4EA0AAE5267A6C
W: The repository ' xenial InRelease' is not signed.
N: Data from such a repository can't be authenticated and is therefore potentially dangerous to use.
N: See apt-secure(8) manpage for repository creation and user configuration details.

This can be fixed by running the following command:

sudo apt-key adv --keyserver hkp:// --recv 4F4EA0AAE5267A6C

Then run sudo apt-get update again. The error messages should disappear.

Step 2

sudo apt-get install php7.1
sudo apt-get install php7.1 php7.1-cli php7.1-common php7.1-json php7.1-opcache php7.1-mysql php7.1-mbstring php7.1-mcrypt php7.1-zip php7.1-fpm
php -v

If there are multiple versions of PHP installed, use the following command to switch between versions:

update-alternatives --config php