Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialSteven Griffiths
3,165 PointsWhy do we use concatenation to add the $product_id to the end of the web address
Hi.
Can't quite get my head around this.
Why do we have to concatenate here? can't we just write something like this:
echo '<a href="shirt.php?id=$product_id">';
Thanks in advance
2 Answers
Muhammad Mohsen
Courses Plus Student 10,843 PointsHi Steven,
Because you have single quotation surrounding your string you can't echo it like that
<?php echo '<a href="shirt.php?id=$product_id">'; ?>
the result will be string
<a href="shirt.php?id=$product_id">
In other words, it will consider $product_id as string NOT a variable.
you may also echo it like that:
<?php echo "<a href='shirt.php?id=$product_id'>"; ?>
Simply replace 'single quotations' with "double quotations", Now you can embed variables inside it and it will work just fine.
Jeff Busch
19,287 PointsHi Steven,
If you try it your way you will see that the string "$product_id" is echoed instead of the value of $product_id. Run this code and hover your mouse pointer over the links and look at where the link points.
Jeff
<?php
$product_id = 13;
echo '<a href="shirt.php?id=' . $product_id . '">Link 1</a><br>';
echo '<a href="shirt.php?id=$product_id">Link 2</a>';
?>
Jeff Busch
19,287 PointsAnother way to write that line of code is:
<?php
printf('<a href="shirt.php?id=%d">Link 2</a><br>', $product_id);
?>
Personally, I find the printf() method less confusing.
Steven Griffiths
3,165 PointsGreat. That helped a lot.
Many thanks Jeff.
Steven Griffiths
3,165 PointsSteven Griffiths
3,165 Pointsaaah! nice. thanks Muhammad.
Andrew Shook
31,709 PointsAndrew Shook
31,709 PointsJust to add to Muhammad's earlier comment, if you are using the "double quotes" you can also do it like this so the variable stands out a little:
<?php echo "<a href='shirt.php?id={$product_id}'>"; ?>
On almost all the IDE I've used, if you wrap the variable in curly braces it will change the color so that spotting the variable in the string is easier.