compact() function in PHP


The compact() function creates an array containing variables and their values.. It returns an array with all the variables added to it

Syntax

compact(variable1, variable2)

Parameters

  • variable1 − Can be a string with the variable name, or an array of variables. Required.

  • variable2 − Can be a string with the variable name, or an array of variables. Optional.

Return

The compact() function returns an array with all the variables added to it.

Example

The following is an example −

 Live Demo

<?php
$ELE = "Electronics";
$ACC = "Accessories";
$res = compact("ELE", "ACC");
print_r($res);
?>

Output

The following is the output −

Array
(
[ELE] => Electronics
[ACC] => Accessories
)

Example

Let us see another example −

 Live Demo

<?php
$name = "Tom";
$subject = "Hanks";
$id = "001";
$details = array("name", "subject");
$res = compact($details, "id");
print_r($res);
?>

Output

The following is the output −

Array
(
[name => Tom
[subject] => Hanks
[id] => 001
)

Updated on: 23-Dec-2019

145 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements