Jump to content

Add array element inside function?


phenym

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.