Development

PHP Switch vs if elseif

In PHP if & elseif is something i was always using when in fact a simple switch would have done the job and looked cleaner.

Looking at the following Switch and if else code, they do the same thing.

$status = 1;
switch ($status) {
   case 0:
         echo "Offline";
         break;
   case 1:
         echo "Online";
         break;
   case 2:
         echo "Away";
         break;
}
$status = 1; 
  if($status = 0){
    echo "Offline";
  } elseif ($status = 1) {
    echo "Online";
  } else {
    echo "Away";
  }

We can minify the if else, although it can get confusing especially if you come to edit it in the future.

$status = 1; 
if($status = 0){echo "Offline";} elseif ($status = 1) {echo "Online";} else {echo "Away";};

Switch or if elseif?

Its going to come down to how many options you will have, up to 3 different outcomes in an if else seems to be the limit for me, more than that and a switch just seems cleaner and easier to look at and edit rather than a massive nest of if & elseif.

Share

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

1 year ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

1 year ago

FTP getting array of file details such as size using PHP

Using FTP and PHP to get an array of file details such as size and…

2 years ago

Creating Laravel form requests

Creating and using Laravel form requests to create cleaner code, separation and reusability for your…

2 years ago

Improving the default Laravel login and register views

Improving the default Laravel login and register views in such a simple manner but making…

2 years ago

Laravel validation for checking if value exists in the database

Laravel validation for checking if a field value exists in the database. The validation rule…

2 years ago