Mapping associative array keys to variables with $$ in PHP
Created:20 May 2021 17:49:23 , in Web development
Have you ever tried to map an associative array to variables in such a way, that each newly initialized variable has a name which corresponds to a key in the array and is assigned a value which is found under the key in the array? If you can map array keys and values to variables like that, you will be able to access data in the array without using the name of the array itself, which often saves a lot of typing.
A use case
Here is a use case.
$data = [
'key1' => 'value1',
'key2' => 'value2'
];
function readValue1($data){
return $data['key1'];
}
This is the standard way.
A preferred way would be this:
function readValue1($data){
return $key1;
}
Here is the trick how to achieve it:
function readData($data){
foreach($data as $key => $value){
list($$key) = [$value];
}
return $key;
}
To map an associative array to a set of initialized and assigned to variables the code above uses $$ and list(). In PHP double dollar sign ($$) enables name modification of a variable. List() is a convenient way of assigning a value to a variables.
Conclusion
Technique described above proves extremely useful when an array of data needs to be passed to a template in PHP, and might save you lots of keystrokes if employed. Just include your template file in the place where the function returns.
Tags: php
Author, Copyright and citation
Author
Author of the this article - Sylwester Wojnowski - is a sWWW web developer. He has been writing computer code for the websites and web applications since 1998.
Copyrights
©Copyright, 2024 Sylwester Wojnowski. This article may not be reproduced or published as a whole or in parts without permission from the author. If you share it, please give author credit and do not remove embedded links.
Computer code, if present in the article, is excluded from the above and licensed under GPLv3.
Citation
Cite this article as:
Wojnowski, Sylwester. "Mapping associative array keys to variables with $$ in PHP." From sWWW - Code For The Web . https://swww.com.pl//main/index/mapping-associative-array-keys-to-variables-with-in-php
Add Comment