1

I'm working on displaying information about users on their profile pages.

I want to display a field; if this field is not completed then I display a text message, else, I display its value.

I've written this code:

<?php
     $username = $user_profile['field_username'];

     if($username == "") {
       echo 'Please enter a user';
     } else {
       print render ($user_profile['field_username']);
     }
?>

I get this error:

Undefined index : field_username

But the code is working properly.

1

The error:

Undefined index : field_username

informing you that you've Undefined index in your array.

It is similar to:

PHP: Notice: Undefined variable

which says that you've Undefined variable.

Either way, it is just a notice, so the code always would work in that kind of error without affecting any functionality. These kind of messages are displayed on the screen, to help programmers to track the potential code issues.

Run-time notices. Indicate that the script encountered something that could indicate an error, but could also happen in the normal course of running a script.php.net


In your case the notice in the following code:

$username = $user_profile['field_username'];

means that PHP couldn't find field_username key inside the $user_profile array. This could mean several things, such as typos, missing field name, loading empty object or the one without that field, etc.

You can of course disable that kind of errors, but the real problem is that your code isn't written well and it takes some time and experience to follow the coding standards which helps you to avoid such issues.

To avoid the notice, your code can be simplified to one-line of code:

echo !empty($user_profile['field_username']) ? render($user_profile['field_username']) : t('Please enter a user');

If you've more questions about your code quality, you can always ask at Code Review Stack Exchange.

For more reading, check: PHP: “Notice: Undefined variable” and “Notice: Undefined index” at SO

| improve this answer | |
1

With the following line of your code:

$username = $user_profile['field_username'];

It always gets executed and check index field_username. So in case if the index doesn't exist it throws error.

If you replace your code with the following

if(empty($user_profile['field_username'])) {
  echo 'Please enter an user';
} else {
  print render ($user_profile['field_username']);
}

It will not always check field_username index but only if it is not empty.

| improve this answer | |

Not the answer you're looking for? Browse other questions tagged or ask your own question.