compact
Gathers variables into an array by their names.
Syntax
compact(array|string $var_name, array|string ...$var_names): arrayParameters
| Parameter | Type | Description |
|---|---|---|
| $var_name | array|string | The name of a variable without the `$` sign. |
| ...$var_names | array|string | The names of the other variables. |
Return value
arrayA "name => value" array.
Examples
Variables into an array:
<?php
$title = 'Tea';
$price = 250;
echo json_encode(compact('title', 'price'));Output:
{"title":"Tea","price":250}Notes
Often used to pass data to a template: compact('posts', 'user') is shorter than ['posts' => $posts, 'user' => $user].
See also
- extract — Creates variables from the keys of an array.
- array_combine — Creates an array from two lists: keys and values.
In the tutorial
- Arrays — Lists and associative arrays in PHP — creating, changing, iterating and useful functions.