PHP compact() Function

PHP compact Function


Definition :

The compact() function creates an array from variables and their values.

Syntax:

The basic syntax of the compact() function is given with:

     compact(varname1varname2, ...);

Parameters:

The compact() function accepts the following parameters.

Parameter Description
varname1 Required. Can be a string representing variable name, or an array of variables.
varname2, ... Optional. Can be a string representing variable name, or an array of variables. Multiple parameters are allowed.

Example1 : we can see below example how to Create an array from variables and their values

 

Output :

Array
(
    [f_name] => Web
    [M_name] => Designing
    [L_name] => House
)

Note: The compact() function can take several parameters. Each parameter can be either a string containing the name of the variable, or an array of variable names. The array can further contain other arrays of variable names inside it; compact() handles it recursively.

Example2 : We can also pass an array of variable names to this function as shown in the following example

Output : 

Array
(
    [f_name] => Web
    [M_name] => Designing
    [L_name] => House

)