replace index loop with foreach