PHP: Quickly Generate An Array From Variables With The compact() Function

Do you want to build an array in PHP, which should contain existing variables? Well, there is an easy way to do this. PHP has a very cool function for this to do. You can use the variable’s name as the key and the variables value as the value.


Advertisement

Just use the compact() function. It’s really simple to use. Here’s an Example:

<?php
$name = 'John';
$age = 25;
$city = 'Somewhere';
 
$arr = compact('name', 'age', 'city');
var_dump($arr);
?>

which will output this:

array(3) {
  ["name"]=>
  string(4) "John"
  ["age"]=>
  int(25)
  ["city"]=>
  string(9) "Somewhere"
}

You can also use arrays as variables. The compact() function will handle it recursively.

<?php
$name = 'John';
$age = 25;
$city = 'Somewhere';
$hobbies = array('Running', 'Sleeping');
 
$arr = compact('name', 'age', 'city', 'hobbies');
var_dump($arr);
?>

which will output this:

array(4) {
  ["name"]=>
  string(4) "John"
  ["age"]=>
  int(25)
  ["city"]=>
  string(9) "Somewhere"
  ["hobbies"]=>
  array(2) {
    [0]=>
    string(7) "Running"
    [1]=>
    string(8) "Sleeping"
  }
}

And it can even handle associative arrays:

<?php
$name = 'John';
$age = 25;
$city = 'Somewhere';
$hobbies = array('Running', 'Sleeping');
$fitness = array('morning'=>'Planks', 'evening'=>'nothing');
 
$arr = compact('name', 'age', 'city', 'hobbies', 'fitness');
var_dump($arr);
?>

which will output this:

array(5) {
  ["name"]=>
  string(4) "John"
  ["age"]=>
  int(25)
  ["city"]=>
  string(9) "Somewhere"
  ["hobbies"]=>
  array(2) {
    [0]=>
    string(7) "Running"
    [1]=>
    string(8) "Sleeping"
  }
  ["fitness"]=>
  array(2) {
    ["morning"]=>
    string(6) "Planks"
    ["evening"]=>
    string(7) "nothing"
  }
}

You see, this PHP function is a really cool helper for your daily coding. For more information about the compact() function, go to the php.net documentation.

(Visited 11 times, 1 visits today)

Leave a Comment