Free cookie consent management tool by TermsFeed Generator PHP compact | Amir Kamizi
AMIR KAMIZI
Home Blog Courses Books Newsletter Store Membership Buy me a coffee
PHP compact

PHP compact

Last Updated on Feb 14, 2023

Introduction

Compact is one of those functions that helps the readability of your code a lot and also reduces the lines of code you should write.

Compact

Compact gets the name of the variables as argument and then creates an array with name of the variable as the key and the value of the variable as the value of the array element.

 

So let’s say we have a few variables and we want to create an array from them. Without compact I should do something like this:

$twitter = 'pratham';
$feedhive = 'simon';
$php = 'amir';
$people = [
   'twitter'  => $twitter,
   'feedhive' => $feedhive,
   'php'      => $php,
];

But now thanks to compact I can write this

$people = compact('twitter','feedhive','php');
print_r($people);
// Array (
// [twitter]    => pratham
// [feedhive]   => simon
// [php]        => amir
// )

Isn’t it amazing? Using the compact function is going to help you a lot.

Conclusion

Now you know about compact function in PHP.

I recommend you to open a PHP files and try to define an array of variables with compact function.

If you have any suggestions, questions, or opinions, please contact me. I’m looking forward to hearing from you!

Key takeaways

  • compact function in php

Category: programming

Tags: #php #array

Join the Newsletter

Subscribe to get my latest content by email.

I won't send you spam. Unsubscribe at any time.

Related Posts

PHP upload file
Feb 15, 2023 programming

PHP upload file

Today we are going to talk about uploading a file in PHP. Uploading a file is simple but it's very important to know how to handle uploading the files correctly and securely. ...

7 Min Read Read More
PHP Array Reduce
Feb 14, 2023 programming

PHP Array Reduce

Today we are going to talk about array reduce in PHP. Array reduce is a useful function that reduces the given array to a single value using a callback function. ...

3 Min Read Read More
PHP Validate Email
Feb 15, 2023 programming

PHP Validate Email

Today we are going to talk about validating emails in PHP. In a lot of projects you need to validate the emails given by the user to make sure the email address has a correct format. ...

4 Min Read Read More
3 Ways to add Conditional and Loop within HTML
Mar 21, 2023 programming

3 Ways to add Conditional and Loop within HTML

Today we are going to talk about different ways we can add PHP conditionals and loops within HTML . ...

9 Min Read Read More

Recommended Courses

Introduction to Machine Learning in PHP

Introduction to Machine Learning in PHP

Learn to Build Different Machine Learning Models Easily ...

PHP Tutorial Beginner to Advanced

PHP Tutorial Beginner to Advanced

Learn everything you need to start a successful career as a PHP developer ...