How to fix "Undefined index" 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:

&lt;?php
     $username = $user_profile['field_username'];

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


I get this error:


  Undefined index : field_username


But the code is working properly.
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.