PHP compact

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

PHP: compact() function

PHP: Create array containing variables and their values

The compact() function is used to create an array from variables and their values.

Note: compact() looks for a variable with that name in the current symbol table 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.

Version

(PHP 4 and above)

Syntax

compact(variable1, variable2...) 

Parameter

Name

Description

Required /
Optional

Type

variable1

It can be either a string containing the name of the variable, or an array of variable names.

Required

Mixed*

variable2

Same as variable1.

Optional

Mixed*

*Mixed : Mixed indicates that a parameter may accept multiple (but not necessarily all) types.

Return value

An array with variables added to it.

Value Type : Array

Example :

  1. $subject1 = 'Language';  

  2. $subject2 = 'Math';  

  3. $subject3 = 'Geography';  

  4. $subject_list = array('subject2','subject3');  

  5. $result = compact('subject1', $subject_list);  

  6. print_r($result);  

  7. ?>  

Output :

Array ( [subject1] => Language [subject2] => Math [subject3] => Geography )