PHP 8 reference · Array Functions

PHP compact() Function

Create an array from variable names, using each name as the key and the variable's value as the value.

PHP 8 Since 4.0

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

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

Parameters

ParameterDescription
var_name A variable name, or an array of names.
var_names optional More names.

Return value

An array of name => value pairs.

Examples

Variables to an arrayTry it yourself
<?php
$title = "Arrays";
$views = 1200;
print_r(compact("title", "views"));

Output

Array
(
    [title] => Arrays
    [views] => 1200
)
Pass a list of namesTry it yourself
<?php
$name = "Ada";
$role = "admin";
echo json_encode(compact(["name", "role"])), "\n";

Output

{"name":"Ada","role":"admin"}

Version history

VersionChange
PHP 4.0Added
PHP 8.0An undefined variable name raises a warning (a notice since 7.3).

Was this page helpful?