PHP compact Function | Create Array From Variables

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.

Syntax

array compact (‘var1’, ‘var2’, … ‘varN’)

Parameters

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.

Return Value

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.

Examples

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
        )
        */

?>

Conclusion

In conclusion, we discussed the PHP compact Function in this article. You can read more about it on Official PHP Documentation. Additionally, you can learn about more PHP Array Functions on Concatly.

Spread the Knowledge

Leave a Reply

Your email address will not be published. Required fields are marked *