Get "PHP 8 in a Nuthshell" (Now with PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Extract every array keys to variables of the same name in PHP

There are times when you may want to extract every array keys to variables of the same name. For example, you have an array like so.

$user = [
    'name' => 'John Doe',
    'email' => '[email protected]',
];

PHP comes with a handy function called extract() which can be used to extract every array keys to variables of the same name. So, you can do something like this.

$user = [
    'name' => 'John Doe',
    'email' => '[email protected]',
];

extract($user);

echo $name; // John Doe
echo $email; // [email protected]

As you can tell, the extract() function extracts every array keys to variables of the same name. So, you can use the variables directly in your code without even declaring them.

This will overwrite any existing variables with the same name. So, if you have a variable called $name already in your code, it will be overwritten by the value of the $name key in the array.

To avoid this, you can pass the second argument as EXTR_SKIP to the extract() function. This will skip the keys that already exist in the current symbol table.

$name = 'James Bond';

$user = [
    'name' => 'John Doe',
    'email' => '[email protected]',
];

extract($user, EXTR_SKIP);

$name; // James Bond

There are other options as well that you can pass to the extract() function. You can check them out in the official documentation.

A word of caution: The extract() function is considered as a bad practice in PHP since it can lead to unreadable code and makes it hard to debug. So, you should avoid using it in your code as much as possible.

Learn the fundamentals of PHP 8 (including 8.1, 8.2, 8.3, and 8.4), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

Like this article?

Buy me a coffee

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?