Compressing and uncompressing a string with PHP

Today I went on a mission to find a PHP function that I’ve never used before and knew nothing about. The mission was such a success that I have two functions to discuss and honestly, I’m pretty sure I’ll never use them. That being said, if the need ever arises where you need to compress a string (perhaps as a way to save space or bandwidth) you can use gzcompress and gzuncompress when you need to uncompress the string (obviously 😉

Let’s start by compressing our string:

$compressed = gzcompress('Such uncompressed, much length'

And to uncompress:

$uncompressed = gzuncompress($compressed

You can optionally pass in a compression level as the 2nd parameter, the default is 6 as well as an encoding value which defaults to ZLIB_ENCODING_DEFLATE.

If you’ve ever used these functions I’d love to hear about it, comment below!

Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.


If you found this article helpful, please consider buying me a coffee.