acctman
acctman

Reputation: 4349

Am I bloating my coding with IF statements?

I was wondering, do too many IF statements bloat coding and when is it okay not to use them?

These two examples both work the same and I'm the only one editing / using the script. Am I teaching myself bad habits by not adding the IF statement?

if ($en['mm_place']) {
    $tmp = explode(",", $en['mm_place']);
    $en['mm_place'] = $tmp[0].", ".$tmp[1]." ".$tmp[2];
}

is the same as...

$tmp = explode(",", $en['mm_place']);
$en['mm_place'] = $tmp[0].", ".$tmp[1]." ".$tmp[2];

EDIT: using @Francis Avila example I came up with this...

if ($en['mm_wmeet']) {
    $tmp = explode(",", $en['mm_wmeet']);
    for ($i = 0; $i < count($tmp); $i++) {
        $en['mm_wmeet'] = $tmp[$i];
    }
}

Upvotes: 0

Views: 192

Answers (3)

Francis Avila
Francis Avila

Reputation: 31641

In this particular example, they are not the same.

If $en['mm_place'] is empty, then $tmp will not have three elements, so your string construction will be bogus.

Actually what you need is probably this:

if (!empty($en['mm_place'])) { // depending on whether you know if this is set and must be a string.
    $tmp = explode(',', $en['mm_place'], 3);
    if (count($tmp)===3) {
        $en['mm_place'] = "{$tmp[0]}, {$tmp[1]} {$tmp[2]}";
    }
}

Run PHP with E_NOTICE set, and code in such a way that you don't get any notices. PHP requires an extraordinary amount of discipline to use safely and properly because it has so many sloppy misfeatures. Notices will inform you of most bad practices. You will probably end up using lots of if statements.

Upvotes: 1

Dan Simon
Dan Simon

Reputation: 13137

In this kind of situation, where you are checking if an array element exists before operating on it, you should keep the if-statement in the code. Here it will only throw a notice if the element is missing, but in the future you definitely could have similar code that will crash if the element is not set.

Edit: Actually those two code samples are not the same. if $en['mm_place'] is null or not set, the first sample will leave it as such while the second will replace it with ", "

Upvotes: 0

Samus_
Samus_

Reputation: 2992

if they don't serve any purpose then yes, you're bloating.

Upvotes: 1

Related Questions