Using $_SESSION in a Foreach Loop

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 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
	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 :smiley:

Time to change the the way you store things I’d say. :slight_smile:


<?php
session_start();

$_SESSION['products'] = array(
  1 =>  array(
    'name'      => 'foo',
    'serial'    => 'foo-1-foo',
    'price'     => 0.99,
    'quantity'  => 1
  ),
  2 =>  array(
    'name'      => 'bar',
    'serial'    => 'bar-2-bar',
    'price'     => 3.99,
    'quantity'  => 45
  ),
);
?>
<table>
  <thead>
    <tr>
      <th>
        id
      </th>
      <th>
        name
      </th>
      <th>
        serial
      </th>
      <th>
        quantity
      </th>
      <th>
        price
      </th>
      <th>
        sub-total
      </th>
    </tr>
  </thead>
  <tbody>
    <?php foreach($_SESSION['products'] as $id => $product): ?>
      <tr>
        <td><?php echo $id; ?></td>
        <td><?php echo $product['name']; ?></td>
        <td><?php echo $product['serial']; ?></td>
        <td><?php echo $product['quantity']; ?></td>
        <td><?php echo $product['price']; ?></td>
        <td><?php echo $product['price'] * $product['quantity']; ?></td>
      </tr>
    <?php endforeach; ?>
  </tbody>
</table>

Hello,

When you are trying to display the value, you session variable should look like this:

$_SESSION['P_QUANT_'.$key]

or like this

$_SESSION["P_QUANT_$key"]

Hi guys, ok I’m changing the way I store my $_POST data on the previous page. I have seven fields for the operator to enter products, not all will be used but the values of null are still being delivered to the array. Anyway I can only include fields which are NOT empty?

$names = array();
		array_push($names, "$_POST[pname]", "$_POST[pname1]", "$_POST[pname2]");
		print_r($names);

You could pop them in an array and apply a filter.


<?php
$fixture = array(
  null,
  'null',
  '',
  0,
  '0',
  false,
  'false'
);

print_r(
  array_filter(
    $fixture,
    create_function(
      '$subject',
      'return 0 < strlen(trim($subject));'
    )
  )
);

/*
  Array
  (
      [1] => null
      [3] => 0
      [4] => 0
      [6] => false
  )
*/


<?php
$name = array_filter(
  array($_POST['foo'], $_POST['bar']),
  create_function(
    '$subject',
    'return 0 < strlen(trim($subject));'
  )
);

I’d much prefer you to lose the numeric suffix to your elements though and store them properly. :wink:

Can you see how messy this is getting?

Hey Anthony, sure it’s getting pretty messy. What would be the best way to store them? Still learning but seem to be picking things up well. So would you say the best way to store all of this would be dude?

Like this:


$_SESSION['products'] = array(
  1 =>  array(
    'name'      => 'foo',
    'serial'    => 'foo-1-foo',
    'price'     => 0.99,
    'quantity'  => 1
  ),
  2 =>  array(
    'name'      => 'bar',
    'serial'    => 'bar-2-bar',
    'price'     => 3.99,
    'quantity'  => 45
  ),
);


<input type="text" name="products[0][name]" />
<input type="text" name="products[0][price]" />
<input type="text" name="products[1][name]" />
<input type="text" name="products[1][price]" />

:slight_smile:

Hey dude, apologies a little slow today (had no sleep). So how do I get the actual $_POST data into the array? Not quite following your above example?

The magic is, if you use the name syntax above, you automatically get the array you’re after. :wink:

A quick piece of code to clear things up.


<?php
if('POST' === $_SERVER['REQUEST_METHOD']){
  echo '<pre>', print_r($_POST, true) ;
  exit;
  /*
    Array
    (
        [products] => Array
            (
                [0] => Array
                    (
                        [name] => Biscuits
                        [price] => 4.99
                    )
                [1] => Array
                    (
                        [name] => Coffee
                        [price] => 8.99
                    )
            )
    )
*/
}
?>
<html>
  <head>
    <title>Demo</title>
  </head>
  <body>
    <form action="" method="post">
      <input type="text" name="products[0][name]" value="Biscuits" />
      <input type="text" name="products[0][price]" value="4.99" />
      <input type="text" name="products[1][name]" value="Coffee" />
      <input type="text" name="products[1][price]" value="8.99" />
      <input type="submit" value="submit order" />
    </form>
  </body>
</html>

Excuses excuses. :stuck_out_tongue:

Developers don’t need sleep, just coffee and biscuits. :slight_smile:

Hey Anthony! Thanks for your help and patience! :slight_smile: Didn’t realize it was so simple, I’ve been handling things in the most awkward way possible! Really learnt something incredibly useful today! Cheers once again dude :smiley:

Ha ha, sometimes you have to do things the hard way before appreciating the simpler, easier things. No?

I’m happy you’re sorted (for now? :p), go get some sleep.

Anthony.