Thursday, 25 September 2014

compact in PHP

The PHP compact () function is the inverse of extract function.
The PHP compact function is utilized to make an array from variables and their values.
The PHP compact function does variable to array change.

Syntax:

compact(var1,var2...)
var1 : Required. Could be a string with the variable name, or an array of variables.
var2 : Optional. Could be a string with the variable name, or an array of variables. Multiple parameters are permitted.

Example:

<?php
$firstname = "John";
$lastname = "Dsouza";
$age = "32";
$resultarr = compact( "firstname","lastname","age" );
print_r($resultarr);
echo "Using a string that does not match a variable, and an array of variable names:";
$firstname = "John";
$lastname = "Dsouza";
$age = "32";
$name = array("firstname","lastname");
$resultarr = compact($name,"location","age");
print_r($resultarr);
?>

O/P:

Array ( 
        [firstname] => John 
        [lastname] => Dsouza
        [age] => 32 
      )
Using a string that does not match a variable, and an array of variable names:
Array ( 
        [firstname] => John 
        [lastname] => Dsouza
        [age] => 32 
     )

0 comments:

Post a Comment