I have a beginner question about foreach and arrays. I am just practicing and created an array to display provinces in alphabetical order as a drop down box. Except no matter how much I try I seem to only be pulling the last variable from the array.
Ahhh. I see now, so simple.
Thank you hash. I actually didn’t use the double quotes in my actual code, I changed them to single but thanks for pointing that one out.
To have it work now feels great. Even if it is a simple little loop.
Adding slashes is another way of dealing with the nested quote marks you had, but the main reason I posted this is to illustrate a way of organising your code so that you can assemble your select together in one place in your script but postpone its injection into the html stream till it suits you, maybe in the middle of some html:
<form id="Myform" name="Myform" method="post">
<?php echo $province_select ; ?>
... and so on
</form>
If you are a beginner, this method might save you some trouble in the long term.
Gonna disagree there you don’t want to do things like that.
Here is how I would do it
// this is your logic, keep it at least above your presentation, if not in another file/class/etc
$provinces = array("Britsh Columbia", "Alberta", "Saskatchewan", "Manitoba", "Ontario", "Quebec", "New Brunswick", "Newfoundland", "Prince Edward Island", "Nova Scotia", "Yukon", "Northwest Terriroties", "Nunavit");
// now is presentation, <html><head><body> etc is already present
<select>
<?php foreach($provinces as $province): ?>
<option name="<?php echo $province ?>"><?php echo $province ?></option>
<?php endforeach; ?>
</select>
I don’t consider that disagreeing, it is just taking my additional idea and improving it. Its just that you haven’t explained why it is so much better…
Whether the OP will benefit from this extra advice (yours or mine) is debatable, but certainly by posting it here, somebody will.
The explanation is in the comments, I’m not sure where in the code you would put $province_select = … but it belongs in the template, so there’s no point in putting it in a variable when you can just type it out. Hope that makes sense
As a neutral observer I like the way Hash put together the drop down. It looks as if it would be easier to organize and refer back to. I wouldn’t have thought to inject the php into the html tags like that.
Makes perfect sense to me, and I could have suggested that myself.
I am just not convinced that introducing the concept of templates, and presumably the concept of seperation of concerns is going to “make sense” to someone who has posted here because they are asking for help on how to loop through an array using foreach(){}