koolaid Posted September 25, 2009 Share Posted September 25, 2009 Hi all. O.K. i have a sorta goofy block of code here. I know there is a much better way to do this. So i was just looking for a little insight on looping through an array with PHP. here is the code i have. $error_str = ''; if($_POST["email"]) { $email = $_POST["email"]; }else{ $error_str .= "failed to post email"; } if($_POST["info"]) { $info = $_POST["info"]; }else{ $error_str .= "\r\nfailed to post info"; } if($_POST["imagepath"]) { $imagepath = $_POST["imagepath"]; }else{ $error_str .= "\r\nfailed to post image path"; } Now you can see what i am trying to accomplish. Seems to me like a looping through an array would be much cooler. In AS it looks like this var myArray = [item1, item2, item3]; var results:String = ""; for(var i : Number = 0; i < myArray.length; i++) { if(myArray[i] != undefined) { results += "\narray item" + i + " = " + myArray[i]; //this would output something like array item 1 = (whatever the value was) }else{ results += "\narray item" + i + " = undefined"; } } trace(results); /* the above trace would look something like: array item 1 = dog; array item 2 = undefined; array item 3 = cat; */ Can anyone show me how i would properly form a similar loop in php. Or tell me i am all wrong and __________ is the way i should accomplish something like this. Thanks in advance guys. Link to comment https://forums.phpfreaks.com/topic/175500-looping-syntax-structure-question/ Share on other sites More sharing options...
TeNDoLLA Posted September 25, 2009 Share Posted September 25, 2009 This what you looking for, two different ways? <?php $items = array('dog', 'cat', 'parrot'); $results = ''; for ($i = 0, $count = count($items); $i<$count; $i++) { $results .= "<br/>" . $items[$i]; } // Or with foreach when you dont need to worry about missing indexes between. foreach ($items as $item) { $results .= "<br/>" . $item; } echo $results; Link to comment https://forums.phpfreaks.com/topic/175500-looping-syntax-structure-question/#findComment-924752 Share on other sites More sharing options...
koolaid Posted September 25, 2009 Author Share Posted September 25, 2009 Yup exactly what i was looking for. TNX a lot. My original code worked but i am always looking for better ways to do things. Link to comment https://forums.phpfreaks.com/topic/175500-looping-syntax-structure-question/#findComment-924780 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.