Jump to content

Can i do this if not how


Brandon_R

Recommended Posts

Hello guys i am having a bit of trouble looping through arrays. Notice i said arrays

 

I was just wondering if i can do this

 

$array1 = explode($_POST['array1']);
$array2 = explode($_POST['array2']);

foreach ($array1 AS $array1exploded AND $array2 AS $array2exploded)
{

code here to play with the arrays 

}

 

If not could you guys guide me on how to do it.

Link to comment
Share on other sites

hmm not sure if OP wants nested, but rather same level looping.  If the array keys are the same, you can do this:

 

foreach($array1 as $key => $val) {
  echo $val; // echo current $array1 value
  echo $array2[$key]; // echo current $array2 value
}

 

if one is a numeric array ($array1) and one is an associative array ($array2), you can do this:

 

$key = 0;
foreach ($array2 as $val) {
  echo $val; // echo current $array2 (associative) value
  echo $array1[$key]; // echo current $array1 (numeric) value
  $key++;
}

 

If they are both associative but have different keys, you can do this:

 

foreach ($array1 as $val) {
  echo $val; // echo current $array1 value
  echo current($array2); // echo current $array2 value
  next($array2);
}

 

of course, all of these examples assume that both of the arrays have the same number of elements...

Link to comment
Share on other sites

@Alex

 

Seems like im going to try your method. I am going to do some error checking for each foreach. I would like to know which number the foreach loop is on so i can output Input for example Number 7 was incorrectly formatted. Is there any native way to do that or do i have to add counter++ in the foreach to determine the number it is at.

Link to comment
Share on other sites

Are you only checking one variable? Because that's what it sounds like from that description. Because you want to know the index of the element if you should use a for():

 

for($i = 0;$i < count($arr);$i++)
{
    echo $arr[$i];
}

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.