Jump to content

looping syntax structure question


koolaid

Recommended Posts

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

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;

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.