PHP compact() Function
In this chapter you will learn:
- Definition for PHP compact() Function
- Syntax for PHP compact() Function
- Parameter for PHP compact() Function
- Example - Create an array with compact
- Example - Using a string that does not match a variable, and an array of variable names
Definition
The compact() function creates an array from variables and their values.
Syntax
PHP compact() Function has the following syntax.
compact(var1,var2...)
Parameter
Parameter | Is Required | Description |
---|---|---|
var1 | Required. | A string with the variable name, or an array of variables |
var2,... | Optional. | A string with the variable name, or an array of variables. Multiple parameters are allowed. |
Example
Create an array with compact
<?php//from j a v a2 s. c om
$firstname = "James";
$lastname = "Smith";
$age = "23";
$result = compact("firstname", "lastname", "age");
print_r($result);
?>
The code above generates the following result.
Example 2
Using a string that does not match a variable, and an array of variable names:
<?php// j a v a2 s .c o m
$firstname = "James";
$lastname = "Smith";
$age = "23";
$name = array("firstname", "lastname");
$result = compact($name, "location", "age");
print_r($result);
?>
The code above generates the following result.
Next chapter...
What you will learn in the next chapter:
- Definition for PHP count() Function
- Syntax for PHP count() Function
- Parameter for PHP count() Function
- Example - Count element in an array
- Example - Count the array recursively
Home » PHP Tutorial » PHP Array Functions