SitePoint Sponsor

User Tag List

Results 1 to 12 of 12
  1. #1
    SitePoint Evangelist
    Join Date
    Aug 2010
    Posts
    503
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

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

  2. #2
    Twitter: @AnthonySterling silver trophy AnthonySterling's Avatar
    Join Date
    Apr 2008
    Location
    North-East, UK.
    Posts
    6,111
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)
    Time to change the the way you store things I'd say.

    PHP Code:
    <?php
    session_start
    ();

    $_SESSION['products'] = array(
      
    =>  array(
        
    'name'      => 'foo',
        
    'serial'    => 'foo-1-foo',
        
    'price'     => 0.99,
        
    'quantity'  => 1
      
    ),
      
    =>  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>
    @AnthonySterling: I'm a PHP developer, a consultant for oopnorth.com and the organiser of @phpne, a PHP User Group covering the North-East of England.

  3. #3
    SitePoint Member
    Join Date
    Jan 2009
    Posts
    21
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hello,

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

    PHP Code:
    $_SESSION['P_QUANT_'.$key
    or like this

    PHP Code:
    $_SESSION["P_QUANT_$key"

  4. #4
    SitePoint Evangelist
    Join Date
    Aug 2010
    Posts
    503
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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?

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

  5. #5
    Twitter: @AnthonySterling silver trophy AnthonySterling's Avatar
    Join Date
    Apr 2008
    Location
    North-East, UK.
    Posts
    6,111
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)
    You could pop them in an array and apply a filter.
    PHP Code:
    <?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 Code:
    <?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.

    Can you see how messy this is getting?
    @AnthonySterling: I'm a PHP developer, a consultant for oopnorth.com and the organiser of @phpne, a PHP User Group covering the North-East of England.

  6. #6
    SitePoint Evangelist
    Join Date
    Aug 2010
    Posts
    503
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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?

  7. #7
    Twitter: @AnthonySterling silver trophy AnthonySterling's Avatar
    Join Date
    Apr 2008
    Location
    North-East, UK.
    Posts
    6,111
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)
    Like this:
    PHP Code:
    $_SESSION['products'] = array(
      
    =>  array(
        
    'name'      => 'foo',
        
    'serial'    => 'foo-1-foo',
        
    'price'     => 0.99,
        
    'quantity'  => 1
      
    ),
      
    =>  array(
        
    'name'      => 'bar',
        
    'serial'    => 'bar-2-bar',
        
    'price'     => 3.99,
        
    'quantity'  => 45
      
    ),
    ); 
    Code:
    <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]" />
    @AnthonySterling: I'm a PHP developer, a consultant for oopnorth.com and the organiser of @phpne, a PHP User Group covering the North-East of England.

  8. #8
    SitePoint Evangelist
    Join Date
    Aug 2010
    Posts
    503
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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?

  9. #9
    Twitter: @AnthonySterling silver trophy AnthonySterling's Avatar
    Join Date
    Apr 2008
    Location
    North-East, UK.
    Posts
    6,111
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)
    The magic is, if you use the name syntax above, you automatically get the array you're after.
    @AnthonySterling: I'm a PHP developer, a consultant for oopnorth.com and the organiser of @phpne, a PHP User Group covering the North-East of England.

  10. #10
    Twitter: @AnthonySterling silver trophy AnthonySterling's Avatar
    Join Date
    Apr 2008
    Location
    North-East, UK.
    Posts
    6,111
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)
    A quick piece of code to clear things up.
    PHP Code:
    <?php
    if('POST' === $_SERVER['REQUEST_METHOD']){
      echo 
    '<pre>'print_r($_POSTtrue) ;
      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>
    Quote Originally Posted by coxdabd View Post
    Hey dude, apologies a little slow today (had no sleep).
    Excuses excuses.

    Developers don't need sleep, just coffee and biscuits.
    @AnthonySterling: I'm a PHP developer, a consultant for oopnorth.com and the organiser of @phpne, a PHP User Group covering the North-East of England.

  11. #11
    SitePoint Evangelist
    Join Date
    Aug 2010
    Posts
    503
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hey Anthony! Thanks for your help and patience! 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

  12. #12
    Twitter: @AnthonySterling silver trophy AnthonySterling's Avatar
    Join Date
    Apr 2008
    Location
    North-East, UK.
    Posts
    6,111
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)
    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? ), go get some sleep.

    Anthony.
    @AnthonySterling: I'm a PHP developer, a consultant for oopnorth.com and the organiser of @phpne, a PHP User Group covering the North-East of England.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •