Jump to content

Archived

This topic is now archived and is closed to further replies.

Cep

Alter for loop & array to allow only one return instance.

Recommended Posts

Hello,

The following for loop is part of my code which will take in variable colour values (if any) from three table fields.

If one of any of these three fields contains a non standard colour (e.g. one not in the if statement) then the extra_price variable needs to be added once.

The current code is adding extra_price for every instance of a non standard colour (e.g. 2 special colours = 2 lots of extra_price) which is not what I want.

I only want extra_price to appear once and only once if one of the three colour values turns out to be a special colour.

[code]
         $colarray = array($col1,$col2,$col3);

         foreach ($colarray as $colval) {
           if (($colval!="Black") && ($colval!="DkBlue") && ($colval!="LtBlue") && ($colval!="DkRed") && ($colval!="Red") && ($colval!="")) {
              $extra_price = $extra_price + $extra_colour;
           }
         }
[/code]

Share this post


Link to post
Share on other sites
You need to set a flag when you find a non-standard color and then if the flag is set do the addition. Here's how I would do it:
[code]<?php
         $colarray = array($col1,$col2,$col3);
         $nonstand = false;
         foreach ($colarray as $colval) {
              switch($colval) {
                  case 'Black':
                  case 'DkBlue':
                  case 'LtBlue':
                  case 'DkRed':
                  case 'Red':
                     break;  // do nothing here
                  default:
                     $nonstand = true;
            }
        }
        if ($nonstand)
             $extra_price += $extra_colour;
?>[/code]

One of the reasons I use a switch statement is that it's easier to add valid cases.

Ken

Share this post


Link to post
Share on other sites
Well that actually makes a lot of sense, though I take it you would have more then one break; for each of the cases. Thanks!





Share this post


Link to post
Share on other sites
No, when you list multiple cases it's like doing an "OR" or "||" in an if statement. If any of the cases match, do the statement block which in this case is just a "break".

Using switch statements like list is very useful when doing validation of form fields.

Ken

Share this post


Link to post
Share on other sites
Ah cool :) I did wonder.

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.