Would unset array/key help here at all?

I have a function that checks if there is an option value set, if not it returns null. I would like to know if unsetting anything before the return would help and how.

function check_page_option( $id ){
	
	$page_options = get_page_options();
	
	if( empty( $page_options ) ){
		
		return null;
	}
	
	foreach($page_options as $set => $options){
		
		$option_val = akg( $id, $options );
		
		if( isset( $option_val ) ){
			unset( $options,$page_options ); // does it help?
			return $option_val;
		}
	}
			
	return null;
	
}

Any help is appreciated!

If it’s just for memory management, I would expect that the PHP “engine” would automatically unset any variables that are local to the scope of the function, when that function exits.

1 Like

Hi nocniagenti welcome to the forum

Yes, it’s all about scope and memory.

AFAIK, PHP does a fairly good job of GC (Garbage Collection). At least it has never been so much of a problem that I’ve felt a critical need to learn a lot about it.

GC cleans up the memory of variables that are no longer being used, and, might not be needed in other areas of the code.

I don’t think booleans, numerics or maybe even strings need to be worried about too much. But massive arrays have caused some sluggishness for me in the past. It was because of the poor newbie level skills I had at the time. I didn’t understand scope very well and the arrays were hanging around after I was done with them. My “solution” was to explicitly unset them.

IMHO, unset, similar to error suppression and output buffer, are tempting to use to “treat the symptom instead of the cause”. True, there may be some instances where their use is unavoidable, but generally if you find you “need” to use unset it is an indication that the code should be refactored.

2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.