PHP Function Reference

PHP compact() Function



The PHP compact() function creates an array containing variables and their values. This function 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.

For each of the parameter, the function looks for a variable with that name and adds it to the output array such that the variable name becomes the key and the contents of the variable become the value for that key.

Note: Since PHP 7.3.0, the function issues an E_NOTICE level error if a given string refers to an unset variable. Previously, such strings have been skipped.

Syntax

compact(var_name, var_names)

Parameters

var_name Required. Specify a string with the variable name, or an array of variable names.
var_names Optional. Specify a string with the variable name, or an array of variable names. Multiple parameters are allowed.

Return Value

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

Exceptions

Issues an E_NOTICE level error if a given string refers to an unset variable.

Example:

The example below shows the usage of compact() function.

<?php
$first_name = "John";
$last_name = "Knight";
$age = 25;
$city = "London";

//creating an array of variable names
$person = array("first_name", "last_name");

//passing multiple strings and array
//containing variable names
$result = compact($person, "age", "city");

//displaying the result
print_r($result);
?>

The output of the above code will be:

Array
(
    [first_name] => John
    [last_name] => Knight
    [age] => 25
    [city] => London
)

❮ PHP Array Reference