Array Functions
Advertisements

PHP compact() Function

Topic: PHP Array ReferencePrev|Next

Description

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+

Syntax

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

compact(varname1, varname2, ...);

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

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

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

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.


Parameters

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:

<?php
$firstname = "John";
$lastname = "Carter";
$age = "32";

$name = array("firstname", "lastname");
$result = compact($name, "age");
print_r($result);
?>
Advertisements
Bootstrap UI Design Templates