-1

I am new to PHP so please i am sorry if this question is a noob. I don't know its name so couldn't find it. I read it in this piece of code. What does it mean?

Line 5: ${$key}

<?php
    $expected = array( 'carModel', 'year', 'bodyStyle' );

    foreach( $expected AS $key ) {
        if ( !empty( $_POST[ $key ] ) ) {
            ${$key} = $_POST[ $key ];
        } else {
            ${$key} = NULL;
        }
    } 
?>
halfer
  • 19,824
  • 17
  • 99
  • 186
user1263375
  • 663
  • 3
  • 18
  • 35

6 Answers6

3

This is the same as $$key and means a var named $key

i.e.

$test = "foo";

is the same as

$a = "test";
$$a = "foo";
Philipp
  • 15,377
  • 4
  • 35
  • 52
2

It's a variable variable. Please read more here: http://php.net/manual/en/language.variables.variable.php

Michael Härtl
  • 8,428
  • 5
  • 35
  • 62
  • 3
    I dont understand why people down vote these answers, People should be encouraged to read api's and documentation. – gbtimmon Mar 21 '13 at 14:00
1

The notation ${$key} is an alternative writing style to simply $$key which is used for variable variables.

One particular case in which you could use that notation is when you do tricks like this:

$var = 'foo_x';
$key = 'x';
${'foo_' . $x} = 'hello';

echo $foo_x; // hello
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
0

Set variable with name $key.

$var = NULL;

$name = 'var';

${$name} = TRUE;

var_dump($var); // TRUE

As well as:

$$name = TRUE;
user0103
  • 1,246
  • 3
  • 18
  • 36
0

It is a way to use dynmaic variable names. See here: http://php.net/manual/en/language.variables.variable.php

Thargor
  • 1,862
  • 14
  • 24
0

It allows for the use of complex expressions.

It's called complex (curly) syntax, you can find more information at http://php.net/manual/en/language.types.string.php#language.types.string.parsing.complex

llanato
  • 2,508
  • 6
  • 37
  • 59
  • +1. This actually makes an attempt at answering the question :) – Ja͢ck Mar 21 '13 at 13:35
  • Have a look at this post, has a bit more information in the second answer for you. http://stackoverflow.com/questions/5571624/php-syntax-question-what-is – llanato Mar 21 '13 at 13:41
  • The biggest part of that particular answer is simply a rip from the manual page ;-) – Ja͢ck Mar 21 '13 at 13:45