Hướng dẫn
Quảng cáo

Hàm compact() trong PHP

Hướng dẫn cách sử dụng hàm compact() về mảng trong lập trình PHP

Tác dụng của hàm compact()

The compact() function creates an array from variables and their values.

The following table summarizes the technical details of this function.

Return Value: Returns an array with all the variables added to it.
Changelog: Since PHP 7.3.0 this function issues an E_NOTICE level error if a given string refers to an unset variable. Earlier, such strings have been silently skipped.
Version: PHP 4+


The basic syntax of the compact() function is given with:

compact(varname1, varname2, ...);

The following example shows the compact() function in action.

// Sample variables
$brand = "Apple";
$model = "iPhone";
$color = "Black";

// Creating array 
$result = compact("brand", "model", "color");

Note: The compact() function can take several parameters. Each parameter can be either a string containing the name of the variable, or an array of variable names. The array can further contain other arrays of variable names inside it; compact() handles it recursively.


The compact() function accepts the following parameters.

Parameter Description
varname1 Required. Can be a string representing variable name, or an array of variables.
varname2, ... Optional. Can be a string representing variable name, or an array of variables. Multiple parameters are allowed.

More Examples

Here're some more examples showing how compact() function actually works:

You can also pass an array of variable names to this function as shown in the following example:

$firstname = "John";
$lastname = "Carter";
$age = "32";

$name = array("firstname", "lastname");
$result = compact($name, "age");

Bài viết này đã giúp ích cho bạn?

Bài viết mới