PHP - loop through 2 arrays

Posted on 2011-05-03
Last Modified: 2012-05-11
I have 2 fields posted to a page separated by commas; both contain the same number of values when exploded.

How do I create a foreach loop to include both arrays?

I want page with id of 1 to have a position of 1
I want page with id of 154 to have a position of 3
I want page with id of 137 to have a position of 6

$page_id = "1,154,137,202,14,157";
$position = "1,3,6,2,4,5";

$page_id_array = explode(",",$page_id);
$pos_array = explode(",",$position);

//what should go below???
foreach($pos_array as $key => $value){

$query_upd_menu = "UPDATE menu SET position = '".$key."' WHERE page_id = '".$value."'";

Thanks in advance for your help.
Question by:sabecs
    LVL 82

    Accepted Solution

    $page_id = explode(',', '1,154,137,202,14,157');
    $position = explode(',', '1,3,6,2,4,5');
    LVL 82

    Expert Comment

    If you REALLY want to do this via foreach:

    $page_id = explode(',', '1,154,137,202,14,157');
    $position = explode(',', '1,3,6,2,4,5');
    foreach($positions as $i=>$index){
      $newArr[$index] = $page_id[$i];

    Author Closing Comment

    Thanks Hielo.
    LVL 82

    Expert Comment

    Glad to help.


    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Find Ransomware Secrets With All-Source Analysis

    Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

    This is a general how to create your own custom plugin system for your PHP application that you designed (or wish to extend a third party program to have plugin functionality that doesn't have it yet).  This is not how to make plugins for existing s…
    Introduction Many web sites contain image galleries; a common design for these galleries includes a page with a collection of thumbnail images.  You can click on each of the thumbnail images to see the larger version of the image.  This is easily i…
    The viewer will learn how to dynamically set the form action using jQuery.
    The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

    779 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    15 Experts available now in Live!

    Get 1:1 Help Now