Content · Programming · PHP

PHP gzcompress() Function: Usage and Examples

Understand PHP gzcompress() with three examples, return behavior, important pitfalls, and related operations.

1 views Published Oct 16, 2026 Updated Oct 16, 2026

Use gzcompress() when you need to compresses a string using the zlib data format in a PHP application. The examples below show the actual operation and its limitations.

What Is gzcompress() in PHP?

Compresses a string using the zlib data format. The exact signature supported by your installation depends on its PHP version and enabled extensions.

Its syntax is:

gzcompress(string $data, int $level = ..., int $encoding = ...): string|false

Parameters and return value: The parameter types, optional arguments, references, and return type are shown in the signature above. Optional parameters are marked with an ellipsis in this reference signature.

Example 1: Basic Usage

<?php

$compressed = gzcompress("Hello Hello"); echo gzuncompress($compressed);

Output:

Hello Hello

Example 2: Different Input or Behavior

<?php

$compressed = gzcompress(str_repeat("A",100)); echo strlen($compressed) < 100 ? "Smaller" : "Not smaller";

Output:

Smaller

Practical Example: Applying the Function

<?php

$message = "Saved configuration"; $packed = gzcompress($message, 6); echo gzuncompress($packed);

Output:

Saved configuration

Important Behavior and Edge Cases

A compressed value is binary data, not encrypted and not necessarily smaller than the original.

Comparison With Related Functions

ApproachDifference
gzcompress()Compresses a string using the zlib data format.
Related operationgzdeflate() creates raw DEFLATE data instead of zlib-wrapped data.

Common Beginner Mistakes

MistakeCorrect Approach
Ignoring the function-specific limitationA compressed value is binary data, not encrypted and not necessarily smaller than the original.
Confusing this function with a related operationgzdeflate() creates raw DEFLATE data instead of zlib-wrapped data.

Key Takeaways

  • Compresses a string using the zlib data format.
  • A compressed value is binary data, not encrypted and not necessarily smaller than the original.
  • gzdeflate() creates raw DEFLATE data instead of zlib-wrapped data.

Use gzcompress() for the specific operation demonstrated above. Check its prerequisites and handle failure conditions before using it with production data.

Share this resourceSend this page to someone who may find it useful.