PHP compact() function

PHP compact() function

The compact() function in PHP is used to create an array containing variables and their values. It returns the output array whose keys are the variable names, and their corresponding values are array values.

Syntax

compact ( mixed $varname1 [, mixed $... ] ) 

Parameter

varname1 – It accepts several parameters where each parameter can be either a string containing the name of the variable or an array of variable names. Even the array can contain other arrays of variable names inside it.

Return

This function an array with all the variables added to it.

Errors/Exceptions

This function throws an E_NOTICE level error if a given string refers to an unset variable.

Example 1




Output

Array
 (
     [country] => India
     [state] => Haryana
     [city] => Faridabad
 ) 

Example 2

 

Output

Array
 (
     [country] => Array
         (
             [0] => India
             [1] => China
             [2] => Japan 
             [3] => Canada
         )
     [state] => Haryana
     [city] => Faridabad
 ) 

Example 3

 

Output

Array
 (
     [country] => India
     [city] => Faridabad
     [state] => Haryana
 ) 

Example 4

 

Output

Array
 (
 )