PHP compact() Function

What is PHP compact() Function?

If you want to create an associative array from one or more variables, use compact() variables. The function uses name of the variable as array-key and value of the variable as array-value.

Syntax:

compact(var1, var2 … varN)

Parameters:

The Function has 1 required parameter and any number of optional parameters-

var1 (Required): It is a variable name (Check example 1) or an array that contains more variables (Check example 2).

var2… varN (Optional): It is a variable name or an array of variables.

Return Values:

  • The function returns an array including all the variables.
  • If the string is an unset variable, PHP 7.3+ throws an E_NOTICE, PHP 8.0+ throws an E_WARNING
  • If it is not a string or array of string, PHP 8.1+ throws an E_WARNING.

Examples:

Example 1:

<pre>
<?php
$Markup = "HTML";
$Styling = "CSS";
$Scripting = "Javascripot";
$Serverside = "PHP";
$theArray = compact("Markup", "Styling", "Scripting", "Serverside");
print_r($theArray);
?>
</pre>

Output:

Array
(
[Markup] => HTML
[Styling] => CSS
[Scripting] => Javascripot
[Serverside] => PHP
)

Example 2:

<pre>
<?php
$Desktop = "Java";
$Frontend = "HTML";
$Backend = "MySQL";
$Bothside = array("Frontend","Backend");
$theArray = compact("Desktop", "Bothside");
print_r($theArray);
?>
</pre>

Output:

Array
(
[Desktop] => Java
[Bothside] => Array
(
[0] => Frontend
[1] => Backend
)

)

Example 3:

<pre>
<?php
$Markup = "HTML";
$Serverside = "PHP";
$theArray = compact("Markup", "serverside");
print_r($theArray);
?>
</pre>

Output:

Array
(
[Markup] => HTML
[Serverside] => PHP
)

Notes on compact() Function:

  • The opposite function of compact() function is extract().
  • The function works only with variables that are in the current local scope.

Practical Usages:

It is used in MVC frameworks like Laravel, CodeIgnitor to pass data from controller to view.

PHP Version Support:

PHP 4, PHP 5, PHP 7, PHP 8

Summary: PHP compact() Function

The compact() function is a built-in PHP function and part of the PHP’s array functions. It’s a useful way to create an associative array from a list of variables.

Reference:

https://www.php.net/manual/en/function.compact.php