Avoiding array out of index error