How do I write this php code?
How do I write this out properly?
$loccity=array("Atlanta","Boston");
foreach ($loccity as $city) {
$myurl = 'http://$city.mysite.com';
echo $myurl;
}
- Can I just stick $city in the middle of $myurl like 开发者_JAVA百科that?
- Will using a
foreach
loop like this work in this way or is a counter needed?
2. Will using a
foreach
loop like this work in this way or is a counter needed?
Yes, it'll work properly.
1. Can I just stick $city in the middle of $myurl like that?
Almost.
You forgot that variable interpolation doesn't work with single quotes, but with double quotes:
<?php
$loccity = array("Atlanta", "Boston");
foreach ($loccity as $city) {
$myurl = "http://$city.mysite.com";
echo $myurl;
}
// Output: http://Atlanta.mysite.comhttp://Boston.mysite.com
?>
Live demo.
You may also want a newline between items:
<?php
$loccity = array("Atlanta", "Boston");
foreach ($loccity as $city) {
echo "http://$city.mysite.com\n";
}
// Output:
// http://Atlanta.mysite.com
// http://Boston.mysite.com
?>
Live demo.
Replace your single quotes with double quotes.
For good measure, wrap your '$city' in curly brackets. So "http://{$city}.mysite.com/"
Why wouldn't it work? Just use double quotes when using $variable inside text
http://sandbox.phpcode.eu/g/466fd.php
<?php
$loccity=array("Atlanta","Boston");
foreach ($loccity as $city) {
$myurl = "http://$city.mysite.com<br>";
echo $myurl;
}
<?php
$loccity=array("Atlanta","Boston");
foreach ($loccity as $city) {
$myurl = 'http://'.$city.'.mysite.com';
echo $myurl;
}
?>
. operator is concatenation operator.
output
http://Atlanta.mysite.comhttp://Boston.mysite.com
精彩评论