il tuo foreach è fuori dal while, quindi $code è sempre uguale all'ultimo valore che gli hai assegnato nel while
Regole del Forum