Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

compact

Gathers variables into an array by their names.

Syntax

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

Parameters

ParameterTypeDescription
$var_namearray|stringThe name of a variable without the `$` sign.
...$var_namesarray|stringThe 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.

Thanks for reading!

Donate to the site — we work hard for you.