Beginnner needs help with For Each

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
justinomaha
Forum Newbie
Posts: 2
Joined: Mon May 18, 2009 12:15 pm

Beginnner needs help with For Each

Post by justinomaha »

I'm very new to programming so I apologize in advance if this is a stupid question!

I'm need the results of a for each loop saved as a variable. Here is what I'm trying:

Code: Select all

$sitemap = "foreach( $finalurl as $key => $value){
 
echo  '<url><loc>http://www.$mainsiteurl.com/$finalurl[$key]</loc><changefreq>daily</changefreq><priority>0.9</priority></url>';
 
}";
Does anyone know how to do this? Thanks for anyone's help!
Last edited by Benjamin on Mon May 18, 2009 1:01 pm, edited 1 time in total.
Reason: Changed code type from text to php.
Acetylene
Forum Newbie
Posts: 4
Joined: Mon May 18, 2009 12:14 pm

Re: Beginnner needs help with For Each

Post by Acetylene »

Code: Select all

$sitemap = "";
 
foreach( $finalurl as $key => $value){
 
$sitemap .=  '<url><loc>http://www.$mainsiteurl.com/$finalurl[$key]</loc><changefreq>daily</changefreq><priority>0.9</priority></url>';
 
}
 
echo $sitemap; // for testing
 
This should work to build your sitemap as long as your array $finalurl is also working properly. Give it a test and see. The .= adds to the previous value of $sitemap (concatenation). If you used just =, then it would replace the previous value. So:

Code: Select all

 
<?php
$array = array(0=>A, 1=>B, 2=>C);
foreach( $array as $key => $value){
$sitemap =  $value;
}
echo "Sitemap = " . $sitemap;
?>
 
gives you:
 
Sitemap: C
 
but this:
 
 
<?php
$array = array(0=>A, 1=>B, 2=>C);
foreach( $array as $key => $value){
$sitemap .=  $value;
}
echo "Sitemap = " . $sitemap;
?>
 
gives you:

Sitemap: ABC

Good luck!
Last edited by Benjamin on Mon May 18, 2009 1:02 pm, edited 1 time in total.
Reason: Added [code=php] tags.
justinomaha
Forum Newbie
Posts: 2
Joined: Mon May 18, 2009 12:15 pm

Re: Beginnner needs help with For Each

Post by justinomaha »

Thank you very much... that worked great!
Post Reply