Cep Posted October 31, 2006 Share Posted October 31, 2006 I have been reading the manual about the usage of For Each loops with some mild confusion.The reason I am looking at them is because I have a string which is then exploded into an array. I then want to take each element of that array and perform an action on it. As the string can be of varying lengths so too can the number of array elements so I cannot use a standard For loop.So I thought For Each would be the best option but from the examples it seems that For Each will only effect the data of the original array (or copy of) of its elements to another array.Am I losing the plot somewhere or would,[code]foreach ($array as $value) { $newvar = "my values ".$value; myfunciton($value);}[/code]work correctly? Link to comment https://forums.phpfreaks.com/topic/25682-mild-confusion-with-for-each/ Share on other sites More sharing options...
trq Posted October 31, 2006 Share Posted October 31, 2006 There is syntactly nothing wrong with your example. Wether it works or not however depends on what it is you expect it to do. Link to comment https://forums.phpfreaks.com/topic/25682-mild-confusion-with-for-each/#findComment-117232 Share on other sites More sharing options...
Cep Posted October 31, 2006 Author Share Posted October 31, 2006 Well say I have email addresses in the array elements and myfunction is a mailer function of some kind. Would the above code work through each element, assign $newvar, mail the email address and then move onto the next one. Link to comment https://forums.phpfreaks.com/topic/25682-mild-confusion-with-for-each/#findComment-117291 Share on other sites More sharing options...
Psycho Posted October 31, 2006 Share Posted October 31, 2006 Yes. As long as the myfunciton (spelling) is correctly written to send an email to the value passed to it.The one problem with that code is that $newvar is getting reassigned each time through the loop, but you are not taking any action on it. So, each previous value is being lost. So, it doesn't serve any obvious purpose. Link to comment https://forums.phpfreaks.com/topic/25682-mild-confusion-with-for-each/#findComment-117295 Share on other sites More sharing options...
Cep Posted October 31, 2006 Author Share Posted October 31, 2006 Well it was just an example :) but thanks for confirming what the for each actually does. Link to comment https://forums.phpfreaks.com/topic/25682-mild-confusion-with-for-each/#findComment-117365 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.