PHP Compact function

PHP asort() function
PHP count() function

In this article, you will learn to create an array from the variable names and their values. The compact function creates an array from the variables using their names and values.

If the variable name does not match with any variables in the script, it is skipped.

What is the syntax of the compact function in PHP?

compact(var1, var2...)
var1Variable name (string) or array of variable names – Reqiuired
var2,…Further Variable name (string) or array of variable names – Optional
compact function in PHP

Examples of compact function

Example 1. Create an array from the given variables and their values.

<?php
$f_name= "Jawad";
$l_name= "Akhtar";
$age = "24";

$result = compact("f_name", "l_name", "age");

print_r($result);
?>

Example 2. Use the compact function to create an array from variables and use a string that does not match any variable name.

<?php
$f_name= "Jawad";
$l_name= "Akhtar";
$age = "24";

$name = array("f_name", "l_name");
$result = compact($name, "location", "age");

print_r($result);
?>
PHP asort() function
PHP count() function
en English
X
Scroll to Top