w3resource

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:

<?php
$subject1 = 'Language';
$subject2 = 'Math';
$subject3 = 'Geography';
$subject_list = array('subject2','subject3');
$result = compact('subject1', $subject_list);
print_r($result);
?>

Output:

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

View the example in the browser

Practice here online:

See also

PHP Function Reference

Previous: asort
Next: count



Follow us on Facebook and Twitter for latest update.