Check for invalid index before accessing array