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');

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!