Using for and array_flip to simulate multiple foreach. Is there a better way?
-
28-05-2021 - |
Question
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 />";
}
OTHER TIPS
The best i can make for the moment
$arrayList = Array($array1, $array2); // Add every array here
$keyArr = Array();
foreach ($arrayList as $key => $value)
{
// Put the keys of every array in $arrayList in an other array
$keyArr[$key] = array_keys($value);
}
// Loop while $i is lower than the highest index of the bigest array in $arrayList
for ($i = 0; $i < count(max($arrayList )); $i++)
{
// Loop every array in $arrayList
foreach ($arrayList as $arrKey => $arr)
{
// If the array in $arrayList has at least $i element
if ($i < count($arr))
{
// Get the key of the $i-n element in the array (take it from the $keyArr defined above)
$key = $keyArr[$arrKey][$i];
// Get the value of the $i-n element in the array
$val = $arr[$key];
}
}
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow