Home >Backend Development >PHP Tutorial >Detailed explanation of how to use php compact() function

Detailed explanation of how to use php compact() function

藏色散人
藏色散人Original
2019-03-08 13:36:404111browse

The compact() function is a built-in function in PHP, which is used to create arrays using variables. This function is the opposite of the extract() function. It creates an associative array whose keys are variable names and whose corresponding values ​​are array values.

Detailed explanation of how to use php compact() function

Syntax:

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

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

Return value: This function returns an array with all variables added.

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

Example:

输入 : $AS="ASSAM", $OR="ORISSA", $KR="KERELA"
        compact("AS", "OR", "KR");
输出:
Array
(
    [AS] => ASSAM
    [OR] => ORISSA
    [KR] => KERELA
)

The following program illustrates how the compact() function in PHP works:

Example-1:

<?php 
      
$AS = "ASSAM"; 
$OR = "ORISSA"; 
$KR = "KERELA"; 
      
$stats = compact("AS", "OR", "KR"); 
  
print_r($states); 
  
?>

Output:

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

Example-2:

<?php 

$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
)

Related recommendations: "PHP Tutorial

This article is an introduction to the use of the php compact() function. I hope it will be helpful to friends in need!

The above is the detailed content of Detailed explanation of how to use php compact() function. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn