2 minutes reading time (444 words)
Featured 

Beware of these mistakes while coding in PHP

Beware-of-these-mistakes-while-coding-in-PHP

As a PHP developer, I am sure we all write some lines of code every day where we use library functions, creates new functions, Writes for, for each loop and also we use some statements and many more things that we need to do for solving a problem by PHP. Do we use the right library functions in the right place? Do we write correct loops? In my opinion, we do common mistakes while doing these things, so what are those mistakes and how to get rid of it, what will be the solutions for it? These are the common questions that arise in every PHP developer’s mind while coding.  

I will be covering these common mistakes and their solutions in a series of blogs, Let’s start with the first blog of this series.

Misunderstandings of isset()

As the name suggests, isset() function returns true if the item exists and returns false if the item does not exist but it returns false for null values too. This turns into a problematic behavior in some cases and becomes a common source of problems.

Problem/Mistake

Consider the following code snippet:

Code Snippet 1:

$data = getData();
if (!isset($data['keyShouldBeSet']) {
   // do something here if 'keyShouldBeSet' is not set
}

In the above snippet, author of the code wanted to check if ‘keyShouldBeSet’ is set or not in $data and if it is not set, wanted to perform some task there, so let’s understand the statement

Code Snippet 2 :

if(!isset($data['keyShouldBeSet'])) {

// Do something here if ‘keyShouldBeSet’ is not set

}

This if block will execute in two cases.

  1. When the ‘keyShouldBeSet’ is not set.

&

  1. Also When the $data[‘keyShouldBeSet’] = null

So the above logic is flawed.

Solution

For cases, though, where it is important to check if a variable was really set (i.e., to distinguish between a variable that wasn’t set and a variable that was set to null), the array_key_exists() method is a much more robust solution.

For example, we could rewrite the first of the above two examples as follows:

Code Snippet 3:

$data = getData();
if (! array_key_exists('keyShouldBeSet', $data)) {
    // do this if 'keyShouldBeSet' isn't set
}

Moreover, by combining array_key_exists() with get_defined_vars(), we can reliably check whether a variable within the current scope has been set or not:

Code Snippet 4 :

if (array_key_exists('varShouldBeSet', get_defined_vars())) {
    // variable $varShouldBeSet exists in current scope
}

Hope above explanation clears the misunderstanding of isset function. You are welcome to comment on any other way to avoid the above problem.

We will be discussing 'Leaving dangling array references after for each loop' mistake in next blog.

Stay tuned, Suggestions are most welcome, Happy Coding!

0
Invitex 3.0.11 is released

Related Posts