RE: [PHP] Multiple "if()" statements
| From: | tedd | Date: | Fri, 30 Jun 2006 23:26:38 +0000 |
| Subject: | RE: [PHP] Multiple "if()" statements | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-239035@lists.php.net to get a copy of this message | ||
At 4:26 PM +0100 6/30/06, Ford, Mike wrote:
>On 30 June 2006 13:37, tedd wrote:
>
>> At 11:07 PM -0600 6/29/06, John Meyer wrote:
>> > Larry Garfield wrote:
>> > >
>> > >[1] switch is fine if your elseif comparisons are equality
> > based. If they're not equality based, then they don't map to
>> switch as well.
>> >
> > > [2] In other words, if you look at a logical ladder as the roots
> > of the tree, as long as each root has the same number of
>> forks (say each fork ends only one way), your fine with a
>> switch. If you have one, however, that has only one
>> condition, and another that has two, then you need an
>> if...elseif logic tree.
>>
>> Interesting -- can you give me an example?
>
>How about this -- a paraphrase of which occurs in many of my scripts:
>
> if (isset($_POST['id'])):
> $id = $_POST['id'];
> // etc. -- other initializations based on $id
> elseif ($_POST['action']=='add'):
> $id = generate_id();
> // initialize stuff to empty values
> elseif (potential_other_test_to_detect_other_valid_states()):
> // other stuff
> else:
> KaBlooie();
> endif;
>
>Of course, that *could* still be implemented using the switch(TRUE) technique (and I've
>used that elsewhere), but in a case like this instance I prefer the if/elseif construct.
I think the point here is that you said [1] and [2], but you still haven't provided an example.
The following works just as well as your elseif example.
switch (TRUE)
{
case isset($_POST['id']:
$id = $_POST['id'];
break;
case $_POST['action']=='add':
$id = generate_id();
break;
case (potential_other_test_to_detect_other_valid_states()):
break;
default KaBlooie();
break;
}
Additionally, in my timed tests, I find both control structures to be generally equal in speed -- so
I don't find any support for elsif being better matched than switch in any equality based
computations.
So, I believe the choice to use one control structure in preference to the other is purely a
personal one -- and one that has no support stemming from any performance differences, because there
are none.
Thanks for your reply.
tedd
--
------------------------------------------------------------------------------------
http://sperling.com http://ancientstones.com http://earthstones.com