Tutorial :Notice: Undefined variable


With error_reporting(E_ALL); removed, my script works fine, however when I uncomment it, the following notice appears:

Notice: Undefined variable: messages in /home/www/test/register/html/form_1.html.php on line 11


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN">  <html>    <head>      <meta name="generator" content=            "HTML Tidy for Linux/x86 (vers 7 December 2008), see www.w3.org">      <title>Sign in or Register</title>    </head>        <body>    <p><?php displayMessages($messages) ?></p><!-- line 11 -->  

On line 11 there is a function call, which basically iterates over an array argument:

function displayMessages($array)    {      if (!empty($array) && isset($array))      {          foreach ($array as $number => $error)          {              echo '<font size="3" color="#990000">' . "* $error" . "</font></br>";          }          }      elseif (empty($array) || !isset($array) )      {          echo "";      }         elseif (empty($array) || !isset($array))      {          $array = array();          $array = null;      }    }  

I've added the if condition to check if its empty, because sometimes I will pass an empty array.

This is a small part of these three files, it's supposed to be a registration form:

  • index.php
  • output.php
  • form_1.html.php

All found here ( http://pastie.org/1062886 )

The index file checks if the user has filled in out the values and validates them, however if they haven't it'll place an error in the respective error array, the display error function is supposed to display them if there are values in the array passed to it.

I bet the solution is pretty basic, but I am a noob and its making me pull my hair out.


For the displayMessages($messages) function call, make sure $messages exist:

if (isset($messages)) {    displayMessages($messages);  }  

empty() already checks if the variable is set, so the && !isset($array) checks are unnecessary in your code.

The condition for the second elseif branch is equivalent to the first elseif condition, so the second elseif block will never be entered.


<p><?php displayMessages($messages) ?></p>  

That variable does not exist at that point in time.

<p><?php if(isset($messages)) displayMessages($messages); ?></p>  

Calling isset later on in your function won't fix that: your argument has already been set to null (as $messages did not exist), and $array surely exists as a function argument.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »