compact()

1. 定义

该函数返回一个将参数列表中的参数名作为键名、与参数名同名的变量的值作为对应的键值的数组。

注:不要对超全局变量使用该函数。

2. 语法

compact ( mixed $varname1 [, mixed $... ] ) : array

3. 参数说明

参数 可选性 数据类型 描述
$varname1 必需 mixed 变量名,可以是字符串,也可以是包含字符串的一维数组

4. 示例

<?php

// compact()
// 返回一个将参数列表中的参数名作为键名、与参数名同名的变量的值作为对应的键值的数组

$name = '极速教程';
$host = 'https://www.jisuapi.com/';
$contact = '18888888888';

$arr = compact('name', 'host');
var_dump($arr);
/* 输出:
array(2) {
  ["name"]=>
  string(12) "极速教程"
  ["host"]=>
  string(24) "https://www.jisuapi.com/"
}
*/

// 当与参数同名的变量未定义时,将会产生警告
$arr = compact('name', 'notexit');// 输出:Notice: compact(): Undefined variable: notexit

$arr_params = ['name', 'host', 'contact'];
$arr = compact($arr_params);
var_dump($arr);
/* 输出:
array(3) {
  ["name"]=>
  string(12) "极速教程"
  ["host"]=>
  string(24) "https://www.jisuapi.com/"
  ["contact"]=>
  string(11) "18888888888"
}
*/

5. 延展阅读

  • extract():将数组中的每个元素被转为对应的变量,其中数组的键名作为变量名,键值作为对应键名的变量值