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 opposite of 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 comma operator (‘,’). These arguments are of string data type and specify the name of variables which 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 fuction returns an array with all the variables added to it.

Note: Any string passed as a parameter which 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="KERELA"
        compact("AS", "OR", "KR");
Output :
Array
(
    [AS] => ASSAM
    [OR] => ORISSA
    [KR] => KERELA
)

Below program illustrate the working of compact() function in PHP:

Example-1:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

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

Example-2:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?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);
  
?>

chevron_right


Output:

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

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



My Personal Notes arrow_drop_up

Sudipta sahana BTech 2nd year Cse student

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.