compact()函数是PHP中的内置函数,用于使用变量创建数组。这个功能与 extract()函数 。它创建一个关联数组,其键是变量名,其对应的值是数组值。
null
语法 :
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 // 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 // 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 )
参考 : http://php.net/manual/en/function.compact.php
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END