PHP compact is an inbuilt Function in PHP. It creates an array from input variables. It creates an associative array whose key are variable name, and their corresponding value as array values. In this article, we will discuss the PHP compact Function. Also, we will discuss a few examples of using it.
array compact (‘var1’, ‘var2’, … ‘varN’)
The PHP compact Function expects at least one parameter. However, you can pass multiple parameters to the function. The description of the parameters is as follows:
- var1: The first parameter to the function is a string with the name of the variable. You need to pass at least one parameter.
- var2…$varN: Also, you can optionally pass multiple parameters to the function.
You can also pass array as a parameter to the function. In that case, it adds all the elements present in the array as keys in the output array.
Note: Any variable which is undeclared, or contains a null value will be skipped in the final array.
The PHP compact Function returns an array containing keys as input variable names and their corresponding values. All the input variables are present in the final array.
Let’s consider a few examples of using the function.
Example 1: Simple Variables
<?php $name = 'Concatly'; $age = 2; $keywords = 'Knowledge'; $array = compact('name', 'age', 'doesNotExist', 'keywords'); print_r($array); /* Array ( [name] => Concatly [age] => 2 [keywords] => Knowledge ) */ ?>
You can observe the following in the above example:
- The parameters contain the name of the variables to the function.
- The compact Function returns an array containing the variable names as key and their corresponding values.
- Any variable which does not exist is simply skipped in the final array.
Example 2: Passing Arrays
Similarly, you can also pass arrays in the input parameters. The input array contains the name of variables as values.
<?php $name = 'Concatly'; $age = 2; $keywords = 'Knowledge'; $inputArray = array('name', 'keywords'); $array = compact('age', $inputArray); print_r($array); /* Array ( [name] => Concatly [age] => 2 [keywords] => Knowledge ) */ ?>
Vishesh is currently working as a Senior Software Engineer at Naukri.com. He passed out of Delhi College of Engineering in 2016 and likes to play Foosball. He loves traveling and is an exercise freak. His expertise includes Java, PHP, Python, Databases, Design and Architecture.