Jump to content

Recommended Posts

Hello,

 

I have an $errors array set up to log errors. In the normal course of my program I add to this simply by:

 

$errors[] = "This is my error message.";

 

I am now inside a function and want to continue adding to my $errors array.

 

<?php

function TestFunc() {
global $errors;

  // some error occurs
$errors[] = "Some error occurred.";

if (!empty($errors)) {
   echo '<h1><font color="red">Errors encountered:</font></h1>' . "\n";
   echo "<p><font color=\"red\">";
   foreach ($errors as $msg) {
       echo " - $msg<br />\n";
     }
  echo "</font></p>";
}

}

// Main part of program

// some other error occurs
$errors[] = "Some other error occurred."

TestFunc();

if (!empty($errors)) {
   echo '<h1><font color="red">Errors encountered:</font></h1>' . "\n";
   echo "<p><font color=\"red\">";
   foreach ($errors as $msg) {
       echo " - $msg<br />\n";
     }
  echo "</font></p>";
}


?>

 

The function outputs:

 

Some other error occurred.
Some error occurred.

 

But the main part of the program outputs:

 

Some other error occurred.

 

I was able to use the global array in the function and add an element to it, but as soon as I get out of the function php promptly forgets the added element. As far as I can tell, php allows me to modify existing elements inside a global-ed array, but will not allow me to add to it.

 

Can anybody provide any insight or hopefully a workaround? I would really like to use my $errors array inside my function... and get my added messages out.

 

TIA

 

phenym

Link to comment
https://forums.phpfreaks.com/topic/187024-add-array-element-inside-function/
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.