Jump to content

[SOLVED] if vs switch


boby

Recommended Posts

Hello guys!

 

I am working on a script and asking myself which way to go. The script is for adding a new entry to the DB or editing an existing entry. Some of the fields are the same, but I cannot populate the fields that I use to add/edit an entry at the top and then populate if user is editing or if adding new.

 

So, I am now asking what would be better, many IF clauses or a SWITCH?

 

...do common stuff...
if ($action == 'edit')
   ...do edit stuff...

...do common stuff...

if ($action == 'edit')
   ...do edit stuff...

...do common stuff...

if ($action == 'new')
   ...do new entry stuff...

or use the SWITCH like:

switch (action)
{
    case 'edit' :
         ...do edit stuff...
         ...do common stuff...
         ...do common stuff...
        ...do edit stuff...
      break;
   case 'new' :
         ...do common stuff...
         ...do common stuff...
      break;
}

 

If I choose the IF clause, the whole code is here and there. With the switch it would be more structured but I would have some things to write twice once for edit and the same in the new entry case.

 

Thanks for any help!

Regards, Boby

 

 

Later Edit: Or should I use two different files? Here I would have again the same thing, both would have part of the code identical.

Link to comment
https://forums.phpfreaks.com/topic/66704-solved-if-vs-switch/
Share on other sites

Maybe a little late but switch is not only the option to go because it makes your code more readable it also makes your code faster!

Using switch the value of the variable ($action in our case) is only evaluated once while using multiple ifs it is evaluated every time a condition is encountered...

 

Regards,

Kathas

Link to comment
https://forums.phpfreaks.com/topic/66704-solved-if-vs-switch/#findComment-334459
Share on other sites

Archived

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

×
×
  • 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.