Content · Programming · PHP

PHP compact() Function: Usage and Examples

Learn how PHP compact works with practical examples, important behavior, relevant alternatives and common mistakes.

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

Builds an associative array from variables named by strings.

What Is compact() in PHP?

Builds an associative array from variables named by strings.

Its syntax is:

compact(array|string $var_name, array|string ...$var_names): array

Parameters:

  • $var_name — Accepted as array|string; required argument.
  • $var_names — Accepted as array|string ...; required argument.

Return type: array. Undefined variable names generate warnings in modern PHP. Do not pass untrusted names into compact().

Availability: Core PHP.

Example 1: Basic Usage

<?php

$name = "Alex"; $role = "editor"; print_r(compact("name", "role"));

Output:

Array
(
    [name] => Alex
    [role] => editor
)

Undefined variable names generate warnings in modern PHP. Do not pass untrusted names into compact().

Example 2: A Different Input

<?php

$city = "Berlin"; print_r(compact(["city"]));

Output:

Array
(
    [city] => Berlin
)

Undefined variable names generate warnings in modern PHP. Do not pass untrusted names into compact().

Practical Example: Applying It in a Program

<?php

$productName = "Keyboard"; $quantity = 3; $unitPrice = 25; $payload = compact("productName", "quantity", "unitPrice"); print_r($payload);

Output:

Array
(
    [productName] => Keyboard
    [quantity] => 3
    [unitPrice] => 25
)

Undefined variable names generate warnings in modern PHP. Do not pass untrusted names into compact().

Important Behavior and Edge Cases

  • Key behavior: Undefined variable names generate warnings in modern PHP. Do not pass untrusted names into compact().
  • Environment: Core PHP.

Comparison With Related Functions

FunctionPurpose
compact()Builds an associative array from variables named by strings.
extract()extract() creates variables from array keys; compact() creates an array from named variables.

Common Beginner Mistakes

MistakeCorrect Approach
Ignoring this behavior: Undefined variable names generate warnings in modern PHPUndefined variable names generate warnings in modern PHP. Do not pass untrusted names into compact().

Key Takeaways

  • Builds an associative array from variables named by strings.
  • Undefined variable names generate warnings in modern PHP. Do not pass untrusted names into compact().
  • Core PHP.

Summary: Undefined variable names generate warnings in modern PHP. Do not pass untrusted names into compact().

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