Mapping associative array keys to variables with $$ in PHP

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

Sylwester Wojnowski

Author of the above article, Sylwester Wojnowski, enjoys sWWW writing computer code in PHP, JavaScript and BASH, and some other things he wrote more on on the About page of this website.

Copyrights

©Copyright, 2021 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://wojnowski.net.pl//main/index/mapping-associative-array-keys-to-variables-with-in-php

Add Comment

Allowed BB Code - style tags: [b][/b], [i][/i], [code=text][/code],[code=javascript][/code],[code=php][/code],[code=bash][/code],[code=css][/code],[code=html][/code]


I constent to processing my data given through this form for purposes of a reply by the administrator of this website.

Recent Comments

Nobody has commented on this post yet. Be first!