phenym Posted January 3, 2010 Share Posted January 3, 2010 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 Quote Link to comment https://forums.phpfreaks.com/topic/187024-add-array-element-inside-function/ Share on other sites More sharing options...
wildteen88 Posted January 3, 2010 Share Posted January 3, 2010 functions have there own variable scope. When using variables with functions you should pass them as arguments Quote Link to comment https://forums.phpfreaks.com/topic/187024-add-array-element-inside-function/#findComment-987673 Share on other sites More sharing options...
phenym Posted January 3, 2010 Author Share Posted January 3, 2010 functions have there own variable scope. When using variables with functions you should pass them as arguments Thanks... passed them as arguments and works great. function MyFunc (&$errors) { } phenym Quote Link to comment https://forums.phpfreaks.com/topic/187024-add-array-element-inside-function/#findComment-987691 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.