Saturday, November 22, 2025
HomeLanguagesPHP compact() Function

PHP compact() Function

The compact() function is an inbuilt function in PHP and it is used to create an array using variables. This function is the opposite of the extract() function. It creates an associative array whose keys are variable names and their corresponding values are array values. 

Syntax:

array compact("variable 1", "variable 2"...)

Parameters: This function accepts a variable number of arguments separated by a comma operator (‘,’). These arguments are of string data type and specify the name of variables that we want to use to create the array. We can also pass an array as an argument to this function, in that case, all of the elements in the array passed as a parameter will be added to the output array. 

Return Value: This function returns an array with all the variables added to it. 

Note: Any string passed as a parameter that does not match with a valid variable name will be skipped and will not be added to the array. Examples:

Input : $AS="ASSAM", $OR="ORISSA", $KR="KERALA"
        compact("AS", "OR", "KR");
Output :
Array
(
    [AS] => ASSAM
    [OR] => ORISSA
    [KR] => KERALA
)

The below program illustrates the working of the compact() function in PHP.

Example-1

PHP




<?php
// PHP program to illustrate compact() 
// Function
      
$AS = "ASSAM";
$OR = "ORISSA";
$KR = "KERALA";
      
$states = compact("AS", "OR", "KR");
  
print_r($states);
  
?>


Output:

Array
(
    [AS] => ASSAM
    [OR] => ORISSA
    [KR] => KERALA
)

Example-2

PHP




<?php
// PHP program to illustrate compact() 
// function when an array is passed as
// a parameter
  
$username = "max";
$password = "many";
$age = "31";
  
$NAME = array("username", "password");
  
$result = compact($NAME, "age");
      
print_r($result);
  
?>


Output:

Array
(
    [username] => max
    [password] => many
    [age] => 31
)

Reference: http://php.net/manual/en/function.compact.php

RELATED ARTICLES

Most Popular

Dominic
32407 POSTS0 COMMENTS
Milvus
97 POSTS0 COMMENTS
Nango Kala
6785 POSTS0 COMMENTS
Nicole Veronica
11932 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12000 POSTS0 COMMENTS
Shaida Kate Naidoo
6907 POSTS0 COMMENTS
Ted Musemwa
7168 POSTS0 COMMENTS
Thapelo Manthata
6864 POSTS0 COMMENTS
Umr Jansen
6850 POSTS0 COMMENTS