compact()函數是PHP中的內置函數,用於使用變量創建數組。此功能與extract()功能相反。它創建一個關聯數組,其鍵為變量名,其對應值為數組值。
用法:
array compact("variable 1", "variable 2"...)
參數:此函數接受可變數量的參數,以逗號運算符(',')分隔。這些參數是字符串數據類型,並指定我們要用於創建數組的變量的名稱。我們還可以將數組作為此函數的參數傳遞,在這種情況下,作為參數傳遞的數組中的所有元素都將添加到輸出數組。
返回值:此函數返回一個數組,其中添加了所有變量。
注意注意:作為參數傳遞的與有效變量名不匹配的任何字符串都將被跳過,並且不會添加到數組中。
例子:
Input : $AS="ASSAM", $OR="ORISSA", $KR="KERELA"
compact("AS", "OR", "KR");
Output :
Array
(
[AS] => ASSAM
[OR] => ORISSA
[KR] => KERELA
)
以下示例程序旨在說明compact()函數在PHP中的工作:
示例1:
// PHP program to illustrate compact()
// Function
$AS = "ASSAM";
$OR = "ORISSA";
$KR = "KERELA";
$stats = compact("AS", "OR", "KR");
print_r($states);
?>
輸出:
Array
(
[AS] => ASSAM
[OR] => ORISSA
[KR] => KERELA
)
示例2:
// 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);
?>
輸出:
Array
(
[username] => max
[password] => many
[age] => 31
)