Jump to content

More of a theory question on uninitiated variables


Vel

Recommended Posts

This is more of a question of "is it OK and / or correct" and a point of interest to myself (and hopefully others) than anything else. I have a situation where in a multidimensional array I am counting the number of entries in another part of this array. I have this statement:

 

        if($array[$i]['counter'])
            $array[$i]['counter']++;
        else
            $array[$i]['counter'] = 1;

 

It would make sense to me to cut the code down and remove the if statement, and just go with:

 

        $array[$i]['counter']++;

 

Completely ignoring the step of checking to see if it's initialised, and if not initialising it. I'm guessing this isn't totally proper, but is it completely incorrect to do this or is it an acceptable way of saving a couple of lines of code?

Link to comment
Share on other sites

Neither are actually correct. The first example will generate an 'undefined index' notice-level error if the key doesn't exist - you should be using isset. The second does not define the initial value, so what are you expecting to increment? Correct way is:

 

if (!isset($array[$i]['counter'])) {
    $array[$i]['counter'] = 0;
}

$array[$i]['counter']++;

Link to comment
Share on other sites

Neither are actually correct. The first example will generate an 'undefined index' notice-level error if the key doesn't exist - you should be using isset. The second does not define the initial value, so what are you expecting to increment? Correct way is:

 

if (!isset($array[$i]['counter'])) {
    $array[$i]['counter'] = 0;
}

$array[$i]['counter']++;

Sorry, I mistyped it in my haste. I do use isset to check if it exists, and if it does increment it by 1, otherwise set it to 1.

Link to comment
Share on other sites

In PHP, even if null is evaluated as 0, something that is undefined will throw an error before you get the chance to increment it.

 

Yeah, although even relying on those kind of false positive results such as null evaluating as 0 is a bad idea. You should always be over-explicit.

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.