Forum Moderators: coopster

Message Too Old, No Replies

What is the variable interpolation in PHP?

         

ifuturz

11:53 am on Jun 18, 2012 (gmt 0)



What is the variable interpolation in PHP?

rocknbil

3:52 pm on Jun 18, 2012 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Do you mean what it "means?"

Interpolation is basically the extraction of the contained value of a given variable. Storing "hello" in the scalar* variable $foo,

$foo = 'hello';

will interpolate properly raw,

echo $foo;

or when double quoted,

echo "She said $foo";

but NOT when single quoted.

echo 'She said $foo'; // prints out: She said $foo

*scalar values are flat single values, like strings and numbers. Array values are also interpolated but by either a list array index starting at zero or an associative array key.

$list = array ('one', 'two', 'three', 'four');

echo $list[2]; //three

$assoc = array(
'one' => 'uno',
'two' => 'dos',
'three' => 'tres',
'four' => 'quatro'
);

or

$assoc['one'] = 'uno'; // etc.

echo $array['two']; // dos

Arrays don't adhere to the same double quoting rules as scalars. You will need to use curlies to disambiguate,

echo "Spanish for two is {$array['two']}";

or concatenate,

echo "Spanish for two is " . $array['two'];

or use HEREDOC, which is a bit unweildy.

echo <<<END
Spanish for two is $array['two'];
END;