Home  >  Article  >  Backend Development  >  How to use php compact function

How to use php compact function

青灯夜游
青灯夜游Original
2019-05-28 14:24:263082browse

The compact() function is a built-in function in PHP that is used to create arrays using variables. The syntax is compact(var1,var2...), this function accepts a variable number of parameters separated by the comma operator (', '), and then creates an associative array whose key is the variable name and whose corresponding value is the array value.

How to use php compact function

How to use the php compact() function?

php compact() function creates an array containing variable names and their values.

Syntax:

compact(var1,var2...)

Parameters:

var1: Required. Can be a string with a variable name, or an array of variables.

var2,...: optional. Can be a string with a variable name, or an array of variables. Multiple parameters are allowed.

Return value: This function returns an array to which all variables are added.

Note: Any string passed as a parameter that does not match a valid variable name will be skipped and will not be added to the array. Any string that does not have a corresponding variable name is ignored.

Let’s take a look at how to use the php compact() function through an example.

Example 1:

<?php
header("content-type:text/html;charset=utf-8"); 
$firstname = "西门";
$lastname = "灭绝";
$age = "25";
$result = compact("firstname", "lastname", "age");
print_r($result);
?>

Output:

Array ( [firstname] => 西门 [lastname] => 灭绝 [age] => 25 )

Example 2:

<?php
header("content-type:text/html;charset=utf-8"); 
$name = "无忌";
$job = "讲师";
$age = "20";
$result = compact("name", "job", "age");
print_r($result);
?>

Output:

Array ( [name] => 无忌 [job] => 讲师 [age] => 20 )

The above is the detailed content of How to use php compact function. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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