Jump to content

Creating arrays within functions in PHP


Abhyro

Recommended Posts

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

Link to comment
Share on other sites

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.

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.