Home >>PHP Array Functions >PHP compact() Function

PHP compact() Function

PHP compact() Function

PHP compact() function is used to create an array using variables and their values. It is opposite of the extract() function. It creates an associative array having variable names as the keys of the array and their corresponding values are array values.

Syntax:

compact($var1, $var2...);

Parameter Values

Parameter Description
var1 This is a required parameter. This parameter can be a string with the variable name or an array of variables.
var2,... This is an optional parameter. This parameter can be a string with the variable name or an array of variables. 

Here is an example of compact() function in PHP:

<html>
<body>
<pre>
<?php
$name = "Jerry";
$company = "Google";
$work = "Developer";
$result = compact("name", "company", "work");
print_r($result);
?>
</pre>
</body>
</html>
Output:
Array
(
    [name] => Jerry
    [company] => Google
    [work] => Developer
)

Example 2:

<html>
<body>
<pre>
<?php
$name = "Jerry";
$company = "Google";
$work = "Developer";
$home = "Delhi";
$office = "Noida";
$place =array("home","office");
$result = compact("name", "company", "work",$place);
print_r($result);
?>
</pre>
</body>
</html>
Output:
Array
(
    [name] => Jerry
    [company] => Google
    [work] => Developer
    [home] => Delhi
    [office] => Noida
)

No Sidebar ads