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
Syntax
compact(array|string $var_name, array|string ...$var_names): array
Parameters
| Parameter | Description |
|---|---|
var_name |
A variable name, or an array of names. |
var_names optional |
More names. |
Return value
An array of name => value pairs.
Examples
<?php
$title = "Arrays";
$views = 1200;
print_r(compact("title", "views"));
Output
Array
(
[title] => Arrays
[views] => 1200
)<?php
$name = "Ada";
$role = "admin";
echo json_encode(compact(["name", "role"])), "\n";
Output
{"name":"Ada","role":"admin"}Version history
Related
extract()· Create variables from an array's keys and values in the current scope. Never use it on user input.array_combine()· Create an array by using one array for keys and another for values. Both arrays must have the same number of elements.- PHP Arrays · tutorial
- PHP Array Functions · tutorial