English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

PHP Basic Tutorial

PHP Advanced Tutorial

PHP & MySQL

PHP Reference Manual

PHP compact() Function Usage and Examples

PHP Array Function Manual

The compact() function creates an array including variable names and their values

Syntax

compact ( mixed $varname1 , mixed $... );

Definition and Usage

  Create an array containing variables and their values.
For each parameter, compact() looks up the variable name in the current symbol table and adds it to the output array, with the variable name as the key and the content of the variable as the value. In simple terms, it does the opposite of extract(). Returns the array after adding all variables.

Return Value

 Returns the output array containing all added variables.

Exception/Error

 If the string points to an undefined variable, compact() will produce an E_NOTICE level error.

Parameter

Serial NumberParameters and Description
1

varname1(Required)

The compact() function accepts a variable number of arguments. Each argument can be a string containing a variable name or an array containing variable names, which can also contain other arrays with variable names as elements. compact() can handle this recursively.

Online examples

 The compact() function creates an associative array using the given values

<?php
$city = "San Francisco";
$state = "CA";
$event = "SIGGRAPH";
$location_vars = array("city", "state");
$result = compact("event", "nothing_here", $location_vars);
print_r($result);
?>
Test and see‹/›

Output result:

Array
(
    [event] => SIGGRAPH
    [city] => San Francisco
    [state] => CA
)

  PHP Array Function Manual