Refactored and added checks to see if array is empty