Welcome Guest, Not a member yet? Register   Sign In
Can/should a switch be declared in a foreach loop
#1

[eluser]TheFuzzy0ne[/eluser]
Hi everyone. Just a quick question. I wanted to put a switch inside a foreach statement. Now I know these work differently from the if construct, so I thought I'd ask if there's any reason why I shouldn't use a switch. Should I use a switch, or stick to if statements?

Thanks.
#2

[eluser]Colin Williams[/eluser]
How many conditions are there? You don't want to be doing elseif, elseif, elseif, etc.
#3

[eluser]brianw1975[/eluser]
I've never had any problems using a switch inside a foreach. Back in the day i used it to loop through a list of db tables and grab the column name, the data type to output form inputs, labels, etc
#4

[eluser]TheFuzzy0ne[/eluser]
5 conditions, not including the default.

It only occurred to me after I'd submitted the post that the question may have been a bit silly. It was just that, for some strange reason, alarm bells started ringing in my head. It's most likely because I don't often require switches in foreach loops. I googled to try and convince myself I wasn't being paranoid, and I couldn't see any examples of a switch in a foreach loop in any of the links I'd followed, and so started worrying.

Thanks, and sorry for being dense. Hehe.
#5

[eluser]Colin Williams[/eluser]
switch() has a bit of stigma to me, too. I think it's probably the least elegant control structure available.
#6

[eluser]Relexx[/eluser]
It is generally considered that if switch (or similar control structure) is available the its use is preferable to a long list of if elseif, elseif, ... statements (in some languages elseif is not available either). Underlying it may be performing almost the same code. Multiple elseif's may be preferable if you are dealing with sub ranges (eg 1-5, 6-10, ...) opposed to unique values (even with the former if the ranges were uniform then you could do some math to generate a uniform value).




Theme © iAndrew 2016 - Forum software by © MyBB