[PHP]How to delete Memcache variables in PHP?

I’ve never thought about deleting a Memcache key is a difficult task. It took me few hours to figure out a working solution. No kidding. FYI, I am using PHP 5.4

Suppose you store a very expensive data into the Memcache, and you decide to delete it later. According to the PHP documentation, it should be very simple:

$memcache_obj->delete('key_to_delete');

or

memcache_delete($memcache_obj, 'key_to_delete');

However, this method only works with scalar variables, such as string, integer, double, float, Boolean etc. It does not work with non-scalar variables such as array, object etc.

I have tried many different ways, such as setting the value to something else, e.g.,

$memcache->set('key_to_delete', 'deleted');

or making the key to expire immediately:

$memcache->set('key_to_delete', 'deleted', 0, 1);
$memcache->set('key_to_delete', 'deleted', 0, -1);

Unfortunately, none of these methods worked in my case (my variable is a non-scalar array). So, I ended up doing it in a low-level way: Bypassing the PECL-Memcache (PHP Library) and talk to the Memcache server directly. Guess what, it works very well. The variable gets deleted!

function MEMCACHE_DEL_HASH($key){
	
	if ($key == '') return FALSE;
	
	$socket = @fsockopen('localhost', 11211);
	$command = "delete {$key}";
	
	fwrite($socket, $command."\r\n");
	fclose($socket);
	
	return true;
}

And it is super easy to call this function:

MEMCACHE_DEL_HASH('key_to_delete');

Feel free to modify this function such that you can pass in the connector, port or do anything you like.

That’s it! Have fun with Memcache.

–Derrick

Our sponsors: