Jump to content

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


Cep

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]
Link to comment
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
Link to comment
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
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

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.