HomeMenu
Jesus · Bible · HTML · CSS · JS · PHP · SVG · Applications

compact

Description

The compact of Array for PHP creates an array containing variables and their values.

Syntax

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

Parameters

var_name

var_names

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

Returns the output array with all the variables added to it.

Examples

1 · var_name · string

<?

$place = "Mount Rushmore National Memorial";

$var_name = "place";

$return = compact($var_name);

print_r($return);
Array
(
    [place] => Mount Rushmore National Memorial
)

2 · var_name · array

<?

$city = "Keystone";
$state = "South Dakota";

$var_name =
[
    "city",
    "state"
];

$return = compact($var_name);

print_r($return);
Array
(
    [city] => Keystone
    [state] => South Dakota
)

3 · var_names · string

<?

$city = "Keystone";
$state = "South Dakota";
$place = "Mount Rushmore National Memorial";

$var_name =
[
    "city",
    "state"
];
$var_names = "place";

$return = compact($var_name, $var_names);

print_r($return);
Array
(
    [city] => Keystone
    [state] => South Dakota
    [place] => Mount Rushmore National Memorial
)

4 · var_names · array

<?

$place = "Mount Rushmore National Memorial";
$city = "Keystone";
$state = "South Dakota";

$var_name = "place";
$var_names =
[
    "city",
    "state"
];

$return = compact($var_name, $var_names);

print_r($return);
Array
(
    [place] => Mount Rushmore National Memorial
    [city] => Keystone
    [state] => South Dakota
)