How to use php compact function

青灯夜游
Release: 2023-02-22 21:14:01
Original
3085 people have browsed it

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...)
Copy after login

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);
?>
Copy after login

Output:

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

Example 2:

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

Output:

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

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!

Related labels:
php
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template