1

Possible Duplicate:
PHP: “Notice: Undefined variable” and “Notice: Undefined index”

I've skimmed through docs and this site but still unsure. I'm working with Drupal 7.

Printing the variable with this code:

<?php print $info['comments'] ?>

If there are zero comments I get

Notice: Undefined index as a message.

If it exists, it prints the correct #.

Any help would be appreciated. How do I set it so if there are no comments it displays a zero?

Thanks!

Community
  • 1
  • 1
bkrall
  • 195
  • 1
  • 12
  • An undefined index is just an undefined index. There is not more to it than that. You have to give us some context or show us an example of what you trying to do, if you want help with this. – Sverri M. Olsen Dec 19 '12 at 23:42

4 Answers4

5

To print an integer no matter what:

 <?php print @intval($info['comments']) ?>

Or to irrevocably suppress the notice:

 <?php print isset($info['comments']) ? $info['comments'] : 0 ?>
mario
  • 144,265
  • 20
  • 237
  • 291
2

I don't know drupal, and don't know your context exactly, but if you try to access an index that doesn't exists from an array, this kind of notice is displayed.

To avoid such a thing, you can do something like :

if(isset($info['comments'])) {
    print $info['comments'];
}
MaxiWheat
  • 6,133
  • 6
  • 47
  • 76
1

PHP arrays are associative by nature, thus you can have an array composed of all types of keys/values:

arry['stringkey'] = 'somestring';
arry[1] = 'some other string';
etc..

If you were to try and reference an index in the array that is not present without doing any error checking, like so

if(arry[2] == 'some third string')

you'd get an 'undefined index' error. Look into the isset() function for a solution.

ryanbwork
  • 2,123
  • 12
  • 12
0

You could test if the array has that key:

if (array_key_exists('comments', $info)) {
...
}

But I am not sure if that is what you really want to do.

jap1968
  • 7,747
  • 1
  • 30
  • 37