phpforeacharray-flip

Using for and array_flip to simulate multiple foreach. Is there a better way?


Is there a better way to do something like this? This is fine but I'd think there's probably a shortcut to get the same results. I guess to add more arrays easily I could just turn it into a function and have the for loop outside it but still.

Just wondering.

<?
$array1 = array("test1","test2","test3","test4");
$array2 = array("dest1","test2","dest3","dest4");




    for ($i=0; $i<count($array1); $i++) { //FOR STATEMENT TO GET MULTIPLE ARRAYS REGISTERED AS A FOREACH-STYLE 
    $val1 = $array1[$i]; //VALUES GET
    $val2 = $array2[$i];

    $array1 = array_flip($array1); //ARRAY IS FLIPPED FROM KEY => VALUE TO VALUE => KEY SO THAT THE KEYS CAN BE GET. REMEMBER TO SWITCH IT BACK.
    $array2 = array_flip($array2);

    $key1 = $array1[$val1]; //NOW MUST ITERATE THROUGH USING VALUES ABOVE BECAUSE THE KEYS ARE NO LONGER NUMBERS.
    $key2 = $array2[$val2];

    $array1 = array_flip($array1); //SWITCHING IT BACK.
    $array2 = array_flip($array2);

    echo $key1 . "=>" . $val1 . "<br />";
    echo $key2 . "=>" . $val2 . "<br />";

    }




    var_dump($array1);

    ?>

Solution

  • You already have the "keys" for the arrays, $i.

    for ($i=0; $i<count($array1); $i++) {
        $val1 = $array1[$i]; // You're getting the value from the array,
        $val2 = $array2[$i]; // you already have the key, $i
    
        echo $i . "=>" . $val1 . "<br />";
        echo $i . "=>" . $val2 . "<br />";
    }
    

    EDIT: If both arrays have the same keys, you can foreach over one, and get the value from the other.

    foreach($array1 as $key=>$val1){
        $val2 = $array2[$key];
    
        echo $key . "=>" . $val1 . "<br />";
        echo $key . "=>" . $val2 . "<br />";
    }