Unlocking an iPhone 4 requires the carrier unlock the phone, then the phone is erased and restored from a backup after the unlock. If switching to another network with a new SIM card, simply replace the existing SIM card and follow the iPhone's setup instructions.
Unlocking phones in any manner was technically illegal until 2014. However, as of March 2015, cellular phone providers in the United States are required to unlock phones upon customer request by providing an unlock code. Many cell phone providers still have restrictions that must be met before the company provides an unlock code to the customer, such as completing the obligations of a service contract associated with the phone or using a prepaid phone with their services for a certain number of months.
Once the cellular provider unlocks an iPhone 4, the phone must be backed up by connecting it to a computer running iTunes or by performing a backup to iCloud. If a new SIM card is to be inserted, use a paper clip to press the SIM card eject button located in a hole on the right side of the iPhone. Take out the old card and insert the new one into the SIM tray. Replace the tray and complete the iPhone's set-up procedure. Erasing the iPhone's settings from the Settings menu, then restoring the iPhone from its local or iCloud backup is always required.