Jump to content

Declaring Global Variables in Function


neridaj

Recommended Posts

Hi,

 

I'm trying to understand why declaring a variable global within a function is not working. I have a function that displays a table of users and is supposed to set a global variable to true when called in order to let another function know whether or not to display a hyperlink. Here is what I have:

 

function display_users($user_array)
{
  // display the table of users

  // set global variable, so we can test later if this is on the page
  global $user_table;
  $user_table = true;
?>
  <br />
  <form name='user_table' action='delete_users.php' method='post'>
  <table width=300 cellpadding=2 cellspacing=0>
  <?php
  $color = "#000000";
  echo "<tr bgcolor='$color'><td><strong>User</strong></td>";
  echo "<td><strong>Delete?</strong></td></tr>";
  if (is_array($user_array) && count($user_array)>0)
  {
    foreach ($user_array as $user)
    {
      if ($color == "#cccccc")
        $color = "#ffffff";
      else
        $color = "#cccccc";
      // remember to call htmlspecialchars() when we are displaying user data
      echo "<tr bgcolor='$color'><td><a href=\"$user\">".htmlspecialchars($user)."</a></td>";
      echo "<td><input type='checkbox' name=\"del_me[]\"
             value=\"$user\"></td>";
      echo "</tr>"; 
    }
  }
  else
    echo "<tr><td>No users on record</td></tr>";
?>
  </table> 
  </form>
<?php
}

function display_admin_menu()
{
?>
<a href="admin_member.php">Home</a>  | 
<?php
  // only offer the delete option if user table is on this page
  global $user_table;
  if($user_table==true)
    echo "<a href='#' onClick='user_table.submit();'>Delete User</a> | "; 
  else
    echo "<font color='#cccccc'>Delete User</font> | "; 
}

 

 

Thanks for any help,

 

Jason

 

Link to comment
Share on other sites

IIRC, using the word global that way means you defined the variable outside of the function, and want to use it IN the function. I think you need to have the function return it, or maybe use the $_GLOBALS array to set it this way?

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.