PHP compact() function
Today we are going to see compact() function on PHP, although it seems pretty simple what it does, it could help you to save time and will also make your code a bit more verbose.
¿But what it does compact()?
Well, this function creates an array from variables and their values.
For example, if we have the following variables:
some variables$name = "Luis"; $surname = "Orson"; $age = "29";
How would we pass these values to an array without compact?
We probably do something like this:
$name = "Luis"; $surname = "Orson"; $age = "29"; $data = array("name"=>$name, "surname"=>$surname, "age"=>$age); var_dump($data);
on the other hand, with compact, we could do the following:
Using compact$name = "Luis"; $surname = "Orson"; $age = "29"; var_dump(compact("name","surname","age"));
The thing get a bit clear in favor of utilizing compact when we use more data, and more if we are using variables including arrays, cause this is recommended to use it.
If you would like to play with code:
<?php echo "<p>Blastcoding.com compact() function example<p>"; echo "<p>sin compact</p>"; $name = "Luis"; $surname = "Orson"; $age = "29"; $data = array("name"=>$name, "surname"=>$surname, "age"=>$age); var_dump($data);//if we use var_dump we can check what it does echo "<p>con compact</p>"; $name = "Luis"; $surname = "Orson"; $age = "29"; var_dump(compact("name","surname","age")); ?>
Where Can I Use PHP compact?
In the first place, without a doubt, is when we need to save the data after performing validation.
$username = "Nick"; $password = "Mhefue3"; $email = "Nick.carp@example.com"; $userData = compact("username", "password", "email"); saveUserData($userData);
In second place, we can use it when passing data to a template. It doesn’t make sense to create an array named “data” to pass the data:
$title = "Un titulo"; $content = "a lorem ipsum paragraph"; template("pagina.php", compact("title", "content"));
In a 3rd place we have that: we can prepare the data before passing it by using compact, which will create an associative array, and therefore we will get a JSON object.
$status = "success"; $data = ["key" => "value"]; echo json_encode(compact("status", "data"));
And finally, and obviously, when we have to pass an array to a function and its values are separated into different variables.
You can see more functions to work with arrays in PHP at https://blastcoding.com/en/php-array-functions/