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.
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.