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
| Function | Purpose |
|---|---|
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
| Mistake | Correct Approach |
|---|---|
| Ignoring this behavior: Undefined variable names generate warnings in modern PHP | Undefined 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().