Hi all, I'm trying to make my code a little cleaner and thought about using a foreach loop instead of if statements. Can't quite get it to work how I want, I need the last number in the key to increment by one. Here is my original code:

PHP Code:
<?php if ($_SESSION['P_NAME_2']){ ?>
    <tr>
    <td><?=$_SESSION['P_QUANT_2']?></td>
    <td><?=$_SESSION['P_SERIAL_2']?></td>
    <td><?=$_SESSION['P_NAME_2']?></td>
    <td>&pound;<?=vatCalc($_SESSION['P_PRICE_2'],1);?></td>
    <td><?=$vat?>%</td>
    <td>&pound;<?=$_SESSION['P_PRICE_1']?></td>
    <td>&pound;<?=subTotal($_SESSION['P_QUANT_2'], $_SESSION['P_PRICE_2'])?></td>
  </tr>
  <?php ?>
  <?php if ($_SESSION['P_NAME_3']){ ?>
    <tr>
    <td><?=$_SESSION['P_QUANT_3']?></td>
    <td><?=$_SESSION['P_SERIAL_3']?></td>
    <td><?=$_SESSION['P_NAME_3']?></td>
    <td>&pound;<?=vatCalc($_SESSION['P_PRICE_3'],1);?></td>
    <td><?=$vat?>%</td>
    <td>&pound;<?=$_SESSION['P_PRICE_3']?></td>
    <td>&pound;<?=subTotal($_SESSION['P_QUANT_3'], $_SESSION['P_PRICE_3'])?></td>
  </tr>
  <?php ?>
    <?php if ($_SESSION['P_NAME_4']){ ?>
    <tr>
    <td><?=$_SESSION['P_QUANT_4']?></td>
    <td><?=$_SESSION['P_SERIAL_4']?></td>
    <td><?=$_SESSION['P_NAME_4']?></td>
    <td>&pound;<?=vatCalc($_SESSION['P_PRICE_4'],1);?></td>
    <td><?=$vat?>%</td>
    <td>&pound;<?=$_SESSION['P_PRICE_4']?></td>
    <td>&pound;<?=subTotal($_SESSION['P_QUANT_4'], $_SESSION['P_PRICE_4'])?></td>
  </tr>
  <?php ?>
And this is what I've tried to use for the foreach loop:

PHP Code:
    <?php
    
foreach(range(1,$_SESSION['P_NAME_7']) as $key){?>
    <tr>
    <td><?=$_SESSION['P_QUANT_$key']?></td>
    <td><?=$_SESSION['P_SERIAL_$key']?></td>
    <td><?=$_SESSION['P_NAME_$key']?></td>
    <td>&pound;<?=vatCalc($_SESSION['P_PRICE_$key'],1);?></td>
    <td><?=$vat?>%</td>
    <td>&pound;<?=$_SESSION['P_PRICE_$key']?></td>
    <td>&pound;<?=subTotal($_SESSION['P_QUANT_$key'], $_SESSION['P_PRICE_$key'])?></td>
  </tr>
    <?php ?>
Any advice/help is appreciated as always