PHP compact() 函數(shù)
定義和用法
compact() 函數(shù)創(chuàng)建一個由參數(shù)所帶變量組成的數(shù)組。如果參數(shù)中存在數(shù)組,該數(shù)組中變量的值也會被獲取。
本函數(shù)返回的數(shù)組是一個關(guān)聯(lián)數(shù)組,鍵名為函數(shù)的參數(shù),鍵值為參數(shù)中變量的值。
本函數(shù)執(zhí)行的行為與 extract() 正好相反。
語法
compact(var1,var2...)
參數(shù) | 描述 |
---|---|
var1 | 必需?梢允菐в凶兞棵淖址蛘呤且粋變量數(shù)組。 |
var2 | 可選?梢允菐в凶兞棵淖址蛘呤且粋變量數(shù)組。允許多個參數(shù)。 |
注釋和提示
注釋:任何沒有變量名與之對應(yīng)的字符串都被略過。
例子 1
<?php $firstname = "Peter"; $lastname = "Griffin"; $age = "38"; $result = compact("firstname", "lastname", "age"); print_r($result); ?>
輸出:
Array ( [firstname] => Peter [lastname] => Griffin [age] => 38 )
例子 2
使用沒有對應(yīng)變量名的字符串,以及一個變量名數(shù)組:
<?php $firstname = "Peter"; $lastname = "Griffin"; $age = "38"; $name = array("firstname", "lastname"); $result = compact($name, "location", "age"); print_r($result); ?>
輸出:
Array ( [firstname] => Peter [lastname] => Griffin [age] => 38 )