Image created with Canva

How NOT to write code in PHP — 5 Bad Examples

Serghei Pogor
7 min readApr 1, 2024

--

In all my years as a developer, I’ve seen tons of code, scripts, and apps. Lots of them were what I’d call bad code. But that’s just my opinion.

Everyone thinks their code’s the best, right? Until they have to fix it, that is!

Sometimes, though, I stumble upon code that’s just plain funny. I mean, really unexpected stuff that makes me laugh out loud. And I figured, why not share some of these gems with you?

Now, let me be clear: this isn’t a how-to guide.

The examples I’m sharing here are just for laughs.

Please, please, promise me you won’t use any of them in your own projects.

Seriously, don’t do it!

So, let’s have some fun and explore a few silly examples together.

1. The Chaotic Abbreviation Syndrome

// Bad Example: Abbreviated Variable Names Gone Wild
$ttlAmt = 1000; // Total amount
$acntBal = 500; // Account balance
$tran = 200; // Transaction amount
$tranFee = 10; // Transaction fee
$remBal = $ttlAmt - $tran - $tranFee; // Remaining balance

if ($remBal <= 0) {
$msg = "Insufficient funds";
} else {
$msg = "Transaction successful";
}

echo $msg;

In this example, we encounter a scenario where variable names have been abbreviated incorrectly, leading to confusion and chaos in the code.

Choosing $acntBal over $accountBalance may seem like a time-saving tactic, but it compromises code clarity and maintainability.

By abbreviating variable names, developers introduce unnecessary ambiguity into the codebase. $acntBal lacks the clarity of $accountBalance, making it difficult for team members to quickly discern its purpose. This ambiguity could lead to errors during code maintenance or when collaborating on projects.

Moreover, abbreviated variable names hinder code readability, especially for developers unfamiliar with the codebase. This can slow down the onboarding process for new team members and increase the time spent deciphering the code.

In the long term, the time saved by using abbreviated variable names is outweighed by the potential for confusion and errors. Clear, descriptive variable names like $accountBalance enhance code readability and maintainability, ultimately improving the efficiency of development efforts.

2. The Confusing Code Formatting

// Bad Example: Inconsistent Formatting
$first_name = "John";
$lastName = "Doe";
$email= "john.doe@example.com";

if($lastName =="Doe"){
echo "Welcome, " . $first_name . "!";
} else {
echo "Unknown user.";
}

In this example, we encounter inconsistent formatting practices, where variable names and code structure lack uniformity.

The inconsistency in variable naming conventions, such as $first_name, $lastName, and $email, makes the code harder to follow. While $first_name uses underscores to separate words, $lastName is written in camel case, and $email is written entirely in lowercase. This inconsistency can confuse developers and disrupt the flow of the code.

Moreover, the inconsistent spacing and indentation in the if statement (if($lastName =="Doe")) further contribute to the chaotic nature of the code. Inconsistent formatting like this makes it challenging to read and understand the code's logic, potentially leading to errors or misinterpretations.

To address inconsistent spacing and indentation issues in code, you can use code formatting plugins or tools that integrate directly into your development environment. Here are some popular options:

  1. PHP Code Beautifier and Fixer (PHP-CS-Fixer): This is a widely used tool for automatically fixing PHP coding standards issues, including formatting inconsistencies. It can be integrated into various development environments and CI/CD pipelines.
  2. PHP CodeSniffer: PHP CodeSniffer is a command-line tool that detects violations of coding standards in PHP code. It can be configured to automatically fix many of these issues, including spacing and indentation problems.
  3. Visual Studio Code (VS Code) Extensions: If you’re using VS Code, there are several extensions available that can help with code formatting, such as PHP Intelephense, PHP Namespace Resolver, and PHP Debug.
  4. PhpStorm: PhpStorm is a popular IDE for PHP development that includes built-in code formatting and code inspection tools. It offers extensive customization options for configuring code style rules and automatically fixing formatting issues.
  5. Sublime Text Plugins: If you’re using Sublime Text, there are plugins like PHP Coding Standards Fixer and SublimeLinter-phpcs that can help with code formatting and adherence to coding standards.

3. Inefficient Looping Practices

Here’s another example of bad code practice:

// Bad Example: Inefficient Looping
$numbers = [1, 2, 3, 4, 5];
$total = 0;
for ($i = 0; $i < count($numbers); $i++) {
$total += $numbers[$i];
}
echo "Total: " . $total;

In this example, we encounter inefficient looping that unnecessarily recalculates the length of the array in each iteration of the loop.

The loop iterates over the array $numbers using an index variable $i and calculates the sum of all elements. However, instead of storing the length of the array in a separate variable before the loop, the code calls the count($numbers) function in each iteration of the loop. This results in unnecessary overhead and reduces the efficiency of the code.

Consequences:

  1. Performance Overhead: Calling count($numbers) in each iteration adds unnecessary computational overhead, especially for large arrays.
  2. Readability: The code becomes less readable and more complex due to the repeated function calls within the loop.
  3. Maintenance Challenges: Future modifications to the loop may inadvertently introduce additional function calls or change the behavior of the loop, leading to bugs or unintended consequences.

To improve efficiency and readability, the length of the array should be calculated once before the loop and stored in a separate variable. This eliminates the need for repeated function calls within the loop and improves the performance of the code.

// Improved Example: Efficient Looping
$numbers = [1, 2, 3, 4, 5];
$total = 0;
$length = count($numbers);
for ($i = 0; $i < $length; $i++) {
$total += $numbers[$i];
}
echo "Total: " . $total;

By storing the length of the array in a separate variable $length before the loop, we avoid the performance overhead of repeated function calls and improve the efficiency and readability of the code.

4. Unnecessary Global Variables

// Bad Example: Unnecessary Global Variables
$counter = 0;

function incrementCounter() {
global $counter;
$counter++;
}

incrementCounter();
echo "Counter: $counter";

In this example, the variable $counter is declared outside of any function, making it a global variable. The function incrementCounter() is defined to increment this global variable.

Explanation

  1. Global State: Using global variables introduces a global state, meaning that the variable’s value can be accessed and modified from any part of the code. This can lead to unintended interactions between different parts of the program, making it harder to reason about and debug.
  2. Dependency: Functions that rely on global variables become tightly coupled to those variables. This makes it more difficult to reuse or refactor the code since any changes to the global variable can affect multiple parts of the program.
  3. Testing Challenges: Global variables can complicate unit testing, as their values may change unpredictably throughout the execution of the program. This makes it harder to isolate and test individual components in isolation.

Consequences

  1. Code Complexity: Global variables increase the complexity of the codebase by introducing hidden dependencies and making it harder to understand the flow of data through the program.
  2. Debugging Difficulty: When unexpected behavior occurs, tracking down the source of the issue becomes more challenging due to the potential interactions with global variables.
  3. Maintenance Challenges: Modifying code that relies on global variables requires careful consideration of the potential impact on other parts of the program. This can slow down development and increase the likelihood of introducing bugs.

To improve code quality, global variables should be avoided whenever possible. Instead, consider using function parameters or encapsulating data within objects to limit the scope of variables and reduce dependencies between different parts of the program.

5. Poor Error Handling

// Bad Example: Poor Error Handling
$file = fopen("example.txt", "r");
$content = fread($file, filesize("example.txt"));
fclose($file);

This code attempts to open a file for reading without checking if the operation was successful or handling any potential errors that may occur.

  1. Lack of Error Checking: The code does not check if the fopen() function call succeeds in opening the file. Similarly, it does not handle potential errors that may occur during file reading or closing.
  2. Potential Exceptions: If the file does not exist, cannot be opened due to permissions, or encounters other issues during reading or closing, the code will produce errors or warnings.

Consequences:

  1. Unpredictable Behavior: Without proper error handling, the code’s behavior becomes unpredictable in case of file-related issues.
  2. Security Risks: Failure to handle errors properly can lead to security vulnerabilities, such as file disclosure or unauthorized access.

To improve error handling, use PHP’s built-in error handling mechanisms such as try-catch blocks or conditional statements to handle potential errors gracefully. For example:

// Improved Example: Error Handling
$file = fopen("example.txt", "r");
if ($file) {
$content = fread($file, filesize("example.txt"));
fclose($file);
} else {
echo "Error: Unable to open file.";
}

By checking for errors and handling them appropriately, the code becomes more robust and resilient to unexpected situations, enhancing its reliability and security.

Avoiding common bad coding practices is essential for maintaining code quality, readability, and maintainability.

By addressing issues such as unclear variable naming, excessive nesting, poor error handling, and the use of magic numbers, developers can write more robust and maintainable code.

Implementing best practices, such as descriptive variable naming, modularization, proper error handling, and adherence to coding standards, leads to more reliable software and enhances the overall development process.

Remember, investing time in writing clean and efficient code pays off in the long run, leading to smoother development cycles, fewer bugs, and happier developers.

🔔 Click Subscribe to catch more coding fun.
👏🏻 Love it? Give a big clap.
💬 Got a cool idea or funny coding joke? Drop it in the comments.

Share this with your coding buddies who’d love a good laugh too!

Thanks for hanging out and reading. You rock! 🚀

Hold on a sec!!! Want more of my fun stuff in your inbox? Sign up here! 📩

--

--

Serghei Pogor
Serghei Pogor

Written by Serghei Pogor

Good code is its own best documentation

Responses (1)