Cep Posted March 23, 2006 Share Posted March 23, 2006 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 https://forums.phpfreaks.com/topic/5606-alter-for-loop-array-to-allow-only-one-return-instance/ Share on other sites More sharing options...
kenrbnsn Posted March 23, 2006 Share Posted March 23, 2006 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 https://forums.phpfreaks.com/topic/5606-alter-for-loop-array-to-allow-only-one-return-instance/#findComment-19997 Share on other sites More sharing options...
Cep Posted March 23, 2006 Author Share Posted March 23, 2006 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! Link to comment https://forums.phpfreaks.com/topic/5606-alter-for-loop-array-to-allow-only-one-return-instance/#findComment-20002 Share on other sites More sharing options...
kenrbnsn Posted March 23, 2006 Share Posted March 23, 2006 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 https://forums.phpfreaks.com/topic/5606-alter-for-loop-array-to-allow-only-one-return-instance/#findComment-20004 Share on other sites More sharing options...
Cep Posted March 23, 2006 Author Share Posted March 23, 2006 Ah cool :) I did wonder. Link to comment https://forums.phpfreaks.com/topic/5606-alter-for-loop-array-to-allow-only-one-return-instance/#findComment-20007 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.