Detailed explanation of how to use php compact() function

藏色散人
Release: 2023-04-05 14:32:01
Original
4071 people have browsed it

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"...)
Copy after login

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
)
Copy after login

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); 
  
?>
Copy after login

Output:

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

Example-2:

<?php 

$username = "max"; 
$password = "many"; 
$age = "31"; 
  
$NAME = array("username", "password"); 
  
$result = compact($NAME, "age"); 
      
print_r($result); 
  
?>
Copy after login

Output:

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

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!

Related labels:
php
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template