Image generated with Dall-E 2

10 PHP Functions to Avoid for Better Code Quality

Serghei Pogor
11 min readMay 3, 2024

--

PHP, a big part of building websites, gives us many tools to use. But not all tools are safe. In this article, we’re going to look at ten PHP functions that need careful handling.

Some are old and rusty, others seem harmless, but all have their own risks. It’s like going on a hike and being careful where you step.

Knowing how PHP functions work helps us write code that works well and stays safe. By learning about each function, we can make smart choices and write code that lasts.

So, let’s get started! We’ll learn all about PHP functions together, so you can feel confident and skilled in your coding journey.

1️⃣ eval()

eval() is like opening Pandora's box of security vulnerabilities. By allowing dynamic code execution from a string, it opens the door to potential code injection attacks.

Plus, debugging and maintaining code that's been eval()-ed is like navigating a maze blindfolded - messy and prone to errors.

Why developers use it

Some developers might turn to eval() for its apparent convenience. It can be tempting to use when you need to dynamically execute PHP code stored in a string.

What alternative to use

Instead of eval(), opt for safer alternatives like anonymous functions or more structured code patterns. These alternatives offer the same flexibility without the security risks and debugging headaches.

$code = "echo 'Hello, world!';";
eval($code);

While eval() might seem like a quick fix, it's a dangerous tool that should be avoided whenever possible.

By embracing safer alternatives, you'll keep your codebase secure and maintainable in the long run.

2️⃣ extract()

extract() might seem like a convenient way to turn array keys into variables, but it can lead to namespace pollution and unexpected behavior. If used carelessly, it can overwrite existing variables or introduce security vulnerabilities by exposing sensitive data.

Why developers use it

Developers often use extract() to simplify code and make it more readable by avoiding repetitive array key references.

What alternative to use

Instead of extract(), it's safer to access array values directly using array syntax, like $array['key']. This approach keeps your code explicit and reduces the risk of variable collisions or unintended variable creation.

$userData = ['name' => 'Alice', 'age' => 25];

// Extracting array keys into variables (bad practice)
extract($userData);

echo $name; // Outputs: Alice
echo $age; // Outputs: 25

How it can break your code:

Consider this scenario:

$userData = ['username' => 'admin', 'role' => 'admin'];

// Extracting array keys into variables (bad practice)
extract($userData);

// Later in the code...
$username = 'guest';

In this scenario, $username is overwritten with 'guest', even though it was initially set to 'admin' from the extracted array. This unexpected behavior can lead to bugs that are difficult to trace and fix.

While extract() might seem convenient, it's best avoided due to its potential for introducing bugs and security vulnerabilities. Stick to explicit array access for cleaner and safer code.

3️⃣ ereg()

ereg() was once a popular function for regular expression matching in PHP. However, it's been deprecated since PHP 5.3 and removed entirely in PHP 7. Instead of gracefully exiting stage left, it left behind a trail of codebases still clinging to its outdated syntax like a barnacle on a ship. 🦑

Why developers use it

Some developers might still use ereg() out of habit or because they're working with legacy codebases that haven't been updated. It's like that comfy old sweater you just can't bear to part with, even though it's got more holes than fabric.

What alternative to use

Instead of ereg(), embrace its modern successor: preg_match(). This newer function offers more features, better performance, and full support for Perl-compatible regular expressions.

It's like upgrading from a flip phone to a smartphone 📱 - once you make the switch, you'll wonder how you ever lived without it.

// Using ereg() (deprecated)
if (ereg('^[a-zA-Z0-9]+$', $username)) {
echo 'Valid username';
} else {
echo 'Invalid username';
}

// Using preg_match() (modern alternative)
if (preg_match('/^[a-zA-Z0-9]+$/', $username)) {
echo 'Valid username';
} else {
echo 'Invalid username';
}

It’s time to bid farewell to ereg() and embrace the future with preg_match(). By upgrading your regular expression game, you'll future-proof your code and avoid getting left behind in the PHP history books. 📚

4️⃣ mysql_query()

Ah, mysql_query(), the relic of a bygone era when dinosaurs roamed the web. This function was once the go-to for executing MySQL queries in PHP scripts, but it's been deprecated since PHP 5.5 and removed entirely in PHP 7. 😢 Using mysql_query() opens the floodgates to SQL injection attacks and other security vulnerabilities, leaving your application as vulnerable as a house of cards in a windstorm.

Why developers use it

Some developers might still use mysql_query() out of habit or because they're working with legacy codebases that haven't been updated. It's like that outdated piece of software you keep around because it's familiar, even though it's riddled with security holes.

What alternative to use

Instead of mysql_query(), migrate to either MySQLi or PDO for database interactions. These modern extensions offer prepared statements and parameterized queries, effectively locking the door on SQL injection attacks and other nasties.

// Using mysql_query() (deprecated)
$query = "SELECT * FROM users WHERE username = '$username'";
$result = mysql_query($query);

// Using MySQLi (modern alternative)
$connection = new mysqli($host, $user, $password, $database);
$query = "SELECT * FROM users WHERE username = ?";
$stmt = $connection->prepare($query);
$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result();

It’s time to bid farewell to mysql_query() and embrace the security and flexibility of MySQLi or PDO.

By modernizing your database interactions, you'll safeguard your application against the perils of outdated practices and sail smoothly into the future.

5️⃣ count()

Wait, what?

Isn’t count() one of the most basic and essential functions in PHP?

Well, yes and no. While count() itself isn't inherently bad, it can lead to performance issues when used carelessly.

This function traverses the entire array to count its elements, which can be a performance bottleneck for large arrays. 🐌 If you're using count() in a loop or frequently in your code, it's like adding unnecessary weight to a backpack before a long hike - you'll feel the strain eventually.

Why developers use it

Developers often use count() to quickly determine the number of elements in an array. It's convenient and straightforward, making it a go-to choice for many PHP programmers.

What alternative to use

Instead of relying on count(), consider storing the array length in a variable if you need to use it multiple times within a loop or function. This way, you only traverse the array once, improving performance. Alternatively, if you're only interested in checking if an array is empty or not, you can use empty() or !empty() respectively.

// Using count() in a loop
$array = [1, 2, 3, 4, 5];
for ($i = 0; $i < count($array); $i++) {
echo $array[$i];
}

// Storing array length in a variable
$array = [1, 2, 3, 4, 5];
$length = count($array);
for ($i = 0; $i < $length; $i++) {
echo $array[$i];
}

While count() is a handy function, it's important to use it judiciously, especially in performance-critical code.

By minimizing unnecessary array traversals, you can optimize your code and ensure it runs smoothly, even with large datasets.

6️⃣ array_merge()

Now, don’t get me wrong, array_merge() isn't inherently bad. It's actually quite useful for merging arrays together.

However, it can lead to unexpected results when dealing with associative arrays. 🔄 When merging two associative arrays with the same string keys, array_merge() will overwrite the values of the first array with the values from the second array.

It's like trying to mix oil and water - they just don't blend well together.

Why developers use it

Developers often use array_merge() to combine arrays quickly and easily. It's like throwing all your ingredients into a blender and hoping for the best - sometimes it works, but other times, you end up with a mess.

What alternative to use

Instead of array_merge(), consider using the + operator for merging associative arrays. Unlike array_merge(), the + operator preserves the original keys of the arrays. If you need to merge indexed arrays, you can use array_merge() safely, but be cautious when working with associative arrays.

// Using array_merge() with associative arrays
$array1 = ['a' => 1, 'b' => 2];
$array2 = ['b' => 3, 'c' => 4];
$result = array_merge($array1, $array2);
print_r($result); // Outputs: ['a' => 1, 'b' => 3, 'c' => 4]

// Using + operator for merging associative arrays
$result = $array1 + $array2;
print_r($result); // Outputs: ['a' => 1, 'b' => 2, 'c' => 4]

While array_merge() has its uses, it's essential to understand its behavior, especially when working with associative arrays.

By choosing the appropriate merging technique for your data structures, you can avoid unexpected surprises and ensure your code behaves as expected.

7️⃣ strlen()

Hold on a second, why is strlen() on the list?

Well, while strlen() itself isn't inherently bad, it can lead to unexpected behavior when dealing with multibyte characters. 🤔

This function counts the number of bytes in a string, which works fine for single-byte character encodings like ASCII, but can cause issues with multibyte character encodings like UTF-8. It's like trying to measure the length of a book by counting the number of pages - it might give you a rough estimate, but it doesn't account for variations in page size.

Why developers use it

Developers often use strlen() to determine the length of strings, especially when performing string manipulation or validation tasks.

What alternative to use

Instead of strlen(), consider using mb_strlen() when working with multibyte character encodings like UTF-8. mb_strlen() calculates the length of a string based on the number of characters rather than bytes, making it more accurate for multibyte strings. If you're working exclusively with single-byte character encodings, strlen() is still a valid choice.

Code example:

// Using strlen() with multibyte characters (potentially incorrect)
$string = "こんにちは"; // "こんにちは" means "hello" in Japanese
$length = strlen($string);
echo "Length: $length"; // Outputs: Length: 15 (incorrect)

// Using mb_strlen() for accurate length calculation
$length = mb_strlen($string, 'UTF-8');
echo "Length: $length"; // Outputs: Length: 5 (correct)

While strlen() is a handy function for string manipulation, it's important to use it appropriately, especially when working with multibyte character encodings.

By choosing the right tool for the job, you'll ensure your code behaves as expected across different language and character sets.

8️⃣ implode()

Hold your horses!

Before you start questioning my sanity, let me explain. implode() is a fantastic function for joining array elements into a string, which is essential for many web applications.

However, it's not without its quirks. One potential pitfall is its behavior with non-string elements in the array. 🤯 If your array contains non-string elements, implode() will silently cast them to strings before joining them together.

This can lead to unexpected results, especially if you're expecting specific data types in the resulting string. It's like trying to mix oil and water - they just don't blend well together.

Why developers use it

Developers use implode() because it's convenient and widely supported across different platforms and programming languages.

What alternative to use

Instead of implode(), consider using implode() in combination with array_map() to ensure consistent data types in the resulting string. By mapping a callback function to convert non-string elements to strings before joining them, you can avoid unexpected type conversions and ensure the integrity of your data.

Code example:

// Using implode() with non-string elements (potentially problematic)
$array = [1, 2, 3];
$string = implode(", ", $array);
echo $string; // Outputs: 1, 2, 3 (elements cast to strings)

// Using implode() in combination with array_map() to ensure consistent data types
$array = [1, 2, 3];
$string = implode(", ", array_map('strval', $array));
echo $string; // Outputs: 1, 2, 3 (elements remain as integers)

While implode() is a powerful tool for joining array elements into a string, it's important to be aware of its limitations, especially when dealing with non-string elements.

By using implode() in combination with array_map(), you can ensure consistent data types in the resulting string and avoid unexpected type conversions.

9️⃣ file_get_contents()

Using file_get_contents() might seem straightforward, but it can introduce potential security risks if used improperly. 🚨 This function retrieves the contents of a file as a string, but it doesn't perform any validation or sanitization on the input URL.

Without proper validation, it’s vulnerable to directory traversal attacks and other malicious activities. 💀 Additionally, fetching large files with file_get_contents() can consume significant memory, leading to performance issues, especially in high-traffic applications.

Why developers use it

Developers often use file_get_contents() for its simplicity and convenience when fetching remote files or reading local files into memory. It's like opening a book to read - easy to do and quick to get started.

What alternative to use

Instead of file_get_contents(), consider using the curl extension for fetching remote files, as it provides more control and security features, such as SSL certificate validation and custom request headers. For reading local files, use fopen() and fread() with proper error handling and validation to ensure safe file access.

These alternatives offer greater flexibility and security compared to file_get_contents().

// Using file_get_contents() to fetch a remote file
$url = 'https://example.com/data.txt';
$data = file_get_contents($url);

// Using curl extension for fetching remote files
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
curl_close($ch);

While file_get_contents() is convenient, it's essential to use it with caution, especially when dealing with untrusted input.

By adopting more secure alternatives like the curl extension for remote file fetching and fopen() with proper validation for local file access, you can mitigate security risks and ensure the robustness of your application.

🔟 array_key_exists()

array_key_exists() is commonly used to check if a key exists in an array. However, it has some drawbacks that can lead to unexpected behavior. 🤔 One issue is that it returns true even if the value associated with the key is null.

This can be misleading if you're specifically checking for the presence of a non-null value. Additionally, array_key_exists() can be slower than using the isset() function, especially when dealing with large arrays.

This performance difference can become noticeable in performance-critical applications.

Why developers use it

Developers use array_key_exists() because it's a straightforward way to check for the existence of a key in an array. It's like checking if a door has a keyhole before trying to unlock it - a simple and intuitive approach.

What alternative to use

Instead of array_key_exists(), consider using the isset() function to check for the existence of a key in an array. isset() not only checks if a key exists but also verifies that the associated value is not null.

This provides more accurate results, especially when dealing with potentially null values. Additionally, isset() is generally faster than array_key_exists(), making it a better choice for performance-sensitive applications.

// Using array_key_exists()
$array = ['key' => null];
if (array_key_exists('key', $array)) {
echo 'Key exists';
} else {
echo 'Key does not exist';
}

// Using isset()
$array = ['key' => null];
if (isset($array['key'])) {
echo 'Key exists and is not null';
} else {
echo 'Key does not exist or is null';
}

While array_key_exists() is a convenient function for checking the existence of keys in arrays, it's essential to be aware of its limitations and performance implications.

By considering alternatives like isset(), you can improve the accuracy and efficiency of your array key checks.

While PHP offers a wide range of functions to accomplish various tasks, not all functions are created equal. Some functions, while seemingly convenient, can lead to unexpected behavior, security vulnerabilities, or performance issues if used improperly.

It’s essential to remember that avoiding these functions doesn’t mean avoiding PHP altogether. Instead, developers should strive to understand the limitations of each function and choose the most appropriate tools for the task at hand.

By staying informed about best practices, security concerns, and performance considerations, developers can write more robust, secure, and efficient PHP code.

So, the next time you reach for a PHP function, take a moment to consider its implications and alternatives.

🔔 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 these tips with your fellow friends to help each other succeed together.

Thanks for hanging out and reading. You rock! 🚀

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

--

--