Incrementing array variables

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
fredsnertz
Forum Newbie
Posts: 4
Joined: Fri Aug 28, 2009 12:20 pm

Incrementing array variables

Post by fredsnertz »

I have a script with a line like this:

Code: Select all

$array[$id]++;
I use the web server error logs for debugging and apparently the warnings are tuned way up. Everytime a new value of $id is encountered, I get a warning saying I'm incrementing a variable that doesn't exist. I can do this:

Code: Select all

if (isset($array[$id])) $array[$id]++; else $array[$id]=1;
but that seems like overkill. I can't initialize the array because I have no way to predict the values of $id. Is there a more correct way to do what I'm trying to do or is that second line the best way? Thanks.
User avatar
AbraCadaver
DevNet Master
Posts: 2572
Joined: Mon Feb 24, 2003 10:12 am
Location: The Republic of Texas
Contact:

Re: Incrementing array variables

Post by AbraCadaver »

If $id = 5 and $array[5] doesn't exist then you can't increment it without a notice.
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
Post Reply