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 Example

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 of the key. Simply put, it does the opposite of extract(). Returns the array after adding all variables.

Return Value

 Returns the output array, which includes all the added variables.

Exception/Error

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

Parameter

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, and this array can also contain other arrays whose unit content is variable names. compact() can process recursively.

Online Examples

 The compact() function uses the given values to create a key-value pair array

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

Output Result:

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

  PHP Array Function Manual