PHP compact function

Last Updated: February 17, 2022

compact — Create an array containing variables and their values

Syntax

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

Supports (PHP 4 , PHP 5, PHP 7, PHP 8)

Parameters

Parameter Description
var_name, var_names Each parameter can be either a string containing the name of the variable, or an array of variable names.

Return Value

Returns the output array with variables

Example

$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
)
Test