compact()
compact() — Create array containing variables and their values.
Built-in function of PHP 8.5. The manual lists it as available in PHP 4, PHP 5, PHP 7, PHP 8. This page is the reference card: signature, parameters and return value, plus the changelog and the example the manual provides.
Signature
compact(array|string $var_name, array|string ...$var_names): array
Parameters
| Parameter | Type | What it takes |
|---|---|---|
| ...$var_names | array|string | compact() takes a variable number of parameters. Each parameter can be either a string containing the name of the variable, or an array of variable names. The array can contain other arrays of variable names inside it; compact() handles it recursively. |
Return value
Returns the output array with all the variables added to it.
Example
A runnable snippet:
$city = "San Francisco"; $state = "CA"; $event = "SIGGRAPH"; $location_vars = array("city", "state"); $result = compact("event", $location_vars); print_r($result);
Output:
Array ( [event] => SIGGRAPH [city] => San Francisco [state] => CA )
Changelog
| Version | Change |
|---|---|
| 8.0.0 | If a given string references an unset variable, an E_WARNING level error is now issued. |
| 7.3.0 | compact() now issues an E_NOTICE level error if a given string refers to an unset variable. Formerly, such strings have been silently skipped. |
See also
All PHP 8.5 built-in functions
Reference card built from the PHP manual page compact() (PHP documentation, CC BY 3.0). The page is generated from the manual, so the wording of the parameter and return value text follows php.net.