Abhyro Posted June 7, 2011 Share Posted June 7, 2011 Hi Is it a good practice to create an array withing a function? Also wanted to know how the variables declared within a function behave in PHP. Are these variables destroyed once the function call is over or do they still cling on to the memory allocated to them? In case they are not destroyed it appears to me that with every call that is made to the function, more and more memory would be consumed and finally the program will crash. If this is the case arrays within functions can cause big problems....if anyone can shed light on this it will be of great help....my code has an array which is created withing a function and the program is just crashing without any error msg....hence am suspecting the above mentioned behavior. Thanks Abhijeet Quote Link to comment https://forums.phpfreaks.com/topic/238654-creating-arrays-within-functions-in-php/ Share on other sites More sharing options...
teynon Posted June 7, 2011 Share Posted June 7, 2011 Abhyro, I wasn't sure of the answer, so I did a test. <?php function test($x) { $var[$x]="blah"; } for ($x=0; $x<20; $x++) { $myArray[$x]=1; echo "Loop 1 #{$x} = ".memory_get_usage() ."<br />"; } for ($x=0; $x<20; $x++) { test($x); echo "Loop 2 #{$x} = ".memory_get_usage() ."<br />"; } ?> The results are this: Loop 1 #0 = 89056 Loop 1 #1 = 89144 Loop 1 #2 = 89216 Loop 1 #3 = 89288 Loop 1 #4 = 89360 Loop 1 #5 = 89432 Loop 1 #6 = 89504 Loop 1 #7 = 89576 Loop 1 #8 = 89648 Loop 1 #9 = 89720 Loop 1 #10 = 89792 Loop 1 #11 = 89864 Loop 1 #12 = 89936 Loop 1 #13 = 90008 Loop 1 #14 = 90080 Loop 1 #15 = 90152 Loop 1 #16 = 90224 Loop 1 #17 = 90296 Loop 1 #18 = 90368 Loop 1 #19 = 90440 Loop 2 #0 = 90776 Loop 2 #1 = 90776 Loop 2 #2 = 90776 Loop 2 #3 = 90776 Loop 2 #4 = 90776 Loop 2 #5 = 90776 Loop 2 #6 = 90776 Loop 2 #7 = 90776 Loop 2 #8 = 90776 Loop 2 #9 = 90776 Loop 2 #10 = 90776 Loop 2 #11 = 90776 Loop 2 #12 = 90776 Loop 2 #13 = 90776 Loop 2 #14 = 90776 Loop 2 #15 = 90776 Loop 2 #16 = 90776 Loop 2 #17 = 90776 Loop 2 #18 = 90776 Loop 2 #19 = 90776 So, as you can see, the variables inside the function are being destroyed. Quote Link to comment https://forums.phpfreaks.com/topic/238654-creating-arrays-within-functions-in-php/#findComment-1226386 Share on other sites More sharing options...
teynon Posted June 7, 2011 Share Posted June 7, 2011 Also, if your program is crashing without an error message, you should enable errors. Or you can check your servers PHP error log. Quote Link to comment https://forums.phpfreaks.com/topic/238654-creating-arrays-within-functions-in-php/#findComment-1226389 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.