Page 1 of 1
Is isset() necessary when incrementing undefined variables
Posted: Thu Oct 09, 2008 10:24 am
by alfmarius
I wanted to do the following:
Code: Select all
$array = array();
for ($i=1;$i<=10;$i++) {
$array['count']++;
}
It gave me a
Notice: Undefined index message (I know i can turn these off).
I'm wondering what people think is the "proper" way to do things. Is it ok to increment
a variable not defined? Or should one do something like this instead:
Code: Select all
$array = array();
for ($i=1;$i<=10;$i++) {
if (isset($array['count']) {
$array['count']++;
} else {
$array['count'] = 1;
}
}
First code is more clean, easier to read, easier to punch, but second code is "more correct"?
Re: Is isset() necessary when incrementing undefined variables
Posted: Thu Oct 09, 2008 2:42 pm
by Bill H
Having just defined $array as an empty array (with no elements), why do you need isset()? You know the element does not exist.
Re: Is isset() necessary when incrementing undefined variables
Posted: Thu Oct 09, 2008 2:58 pm
by js2007
I wouldn't check for the element inside the loop, because it's checked as often as the loop is gone through, so 10 times in your example. And that eats not much but does eat performance.
While it is not necessary to define the index before usage I'ld do that before the loop:
Code: Select all
$array = array();
$array['count'] = 0;
and within the loop only:
That's clean and saves you from any errors. Btw why would u want to increment a extra count variable while you have $i for this?
Re: Is isset() necessary when incrementing undefined variables
Posted: Fri Oct 10, 2008 4:12 am
by alfmarius
Thanks for the responds guys!
js2007 wrote:Btw why would u want to increment a extra count variable while you have $i for this?
You are of course absolutely right, i just wanted to illustrate my case without bringing in the case, and maybe my reconstruction of the scenario was a little missguiding.
Anyway, what I actually have is more something like this:
Code: Select all
$array = array();
while (<getting rows from db>) {
if {<this and that>) {
$array['one']++;
}
if {<this and that>) {
$array['two']++;
}
if {<this and that>) {
$array['three']++;
}
if {<this and that>) {
$array['four']++;
}
...and more...
}
So yes i agree it would be better to initialize all of these to 0 instead of the isset, but then my question would be
is this the best practice? What would you guys out there do?
