0

I just need to know what is the meaning of ${$key} in the code. I already searched google but didn't find answers for this code. So please help me understand it ?

<?php
foreach ($_POST as $key => $value) {
    $temp = is_array($value) ? $value : trim($value);

    if (empty($temp) && in_array($key, $required)) {
        $missing[] = $key;
        ${$key} = '';
    } elseif (in_array($key, $expected)) {
        ${$key} = $temp;
    }
}
?>
Rajdeep Paul
  • 16,887
  • 3
  • 18
  • 37
mahmudy-91
  • 81
  • 1
  • 10
  • 8
    You can read more about variable variables on this manual page: http://php.net/manual/en/language.variables.variable.php – mishu Dec 12 '16 at 15:01
  • See the point about `$$` in the duplicate and this answer: http://stackoverflow.com/a/33880044 – Rizier123 Dec 12 '16 at 17:43

2 Answers2

2

Let's say, we have given code:

<?php
$a = 'Hello'; 
$key = 'a'; 

echo ${$key}; 
?>

will print:

Hello

What you are doing here is referring to the value which name is stored in another variable.

malutki5200
  • 1,092
  • 7
  • 15
1

Using ${} is a way to create dynamic variables, example:

${'a' . 'b'} = 'hello world!';
echo $ab; // hello world!

Read more at official documentation.

Bud Damyanov
  • 30,171
  • 6
  • 44
  • 52