0

I know how to combine two arrays in foreach loop using array_combine() function of PHP

But I have three arrays and I want to loop through all of three arrays at a time.

$get_id=$data->get_id;
$get_product=$data->get_product;
$get_comment=$data->get_comment;

foreach (array_combine($get_id, $get_product) as $id => $product) {
    echo "$id - $product<br/>";

}

I want to iterate $get_comment array too in this loop.

Thanks

11
  • 1
    If these arrays are numerically indexed, you could use a for loop. Commented Apr 22, 2014 at 18:42
  • These arrays are having random values from ajax JSON request Commented Apr 22, 2014 at 18:45
  • Not concerned about the values for the time being but the keys assigned to these values... What about the keys... Are they assigned by you or system generated (or as pointed by @AmalMurali) / numerically indexed. Commented Apr 22, 2014 at 18:46
  • @explorecode: I'm talking about their keys, not values. Can you show the print_r() outputs of the array? Commented Apr 22, 2014 at 18:47
  • But how will i get the nth positions of these arrays. And Yes all them will having same size Commented Apr 22, 2014 at 18:49

2 Answers 2

1

I think this might be what you are looking for:

$get_id=$data->get_id;
$get_product=$data->get_product;
$get_comment=$data->get_comment;

foreach($get_id as $i => $id){
    $product = $get_product[$i];
    $comment = $get_comment[$i];
    echo "$id , $product, $comment<br/>";
}

This solution assumes the $get_id, $get_product, and $get_comment arrays are all indexed the same way.

Sign up to request clarification or add additional context in comments.

Comments

0

Combine the arrays before the foreach loop

    $comment_array = array_combine($get_id, $get_comment);
    $product_array = array_combine($get_id, $get_product);
    foreach ($product_array as $id => $product) {
      $comment = $comment_array[$id];
    }

2 Comments

Will it work because $get_id contains alphanumeric characters?
Shouldn't be a problem, all arrays in PHP are associative.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.