March 5, 2013
Why are my variables not interpolated inside strings?
Question by peace
<?php
$array = array('1' => 'one', '2' => 'two','3','three');
foreach($array as $num => $number){
echo 'Numburic: $num <br /> Number: $number';
};
?>
The result I’m looking for:
1. one
2. two
3. three
Answer by Starx
For that output, you have to do:
foreach($array as $num => $number){
echo "$num. $number <br />";
};
Your mistakes as pointed in other answers is using a single quotes to wrap your string with a PHP variable inside. Only when you use "
(double quotes) your variables will be parsed by PHP.
Also your array definition is wrong (Credit: Musa’s Comment). Change
$array = array('1' => 'one', '2' => 'two','3', 'three');
// ^ This is a separate array item
// not its index
To
$array = array('1' => 'one', '2' => 'two','3' => 'three');