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