2

I'm trying to echo out all variables of two arrays with a single foreach loop making a url. Some coding examples will be honored.

I have this so far :

<?php
foreach($menu_names as $menu_name){
echo "<li><a href='?subj= " .urlencode($subjects["id"]). " '>".$menu_name."</a></li>";
}
?>

I want to add one more array within this loop

yusufiqbalpk
  • 282
  • 1
  • 6
  • 18

4 Answers4

9

assume you have the same number of items in those two arrays.

if you want to use foreach(), then the arrays need to have the same index:

foreach ($a as $index => $value)
{
    echo $a[$index] .' '. $b[$index];
}

if the arrays have numeric index, you can just use for():

for ($i = 0; $i < sizeof($a); $i++)
{
    echo $a[$i] .' '. $b[$i];
}
C. Leung
  • 6,218
  • 3
  • 20
  • 32
  • Note, if you use `for`, the arrays need to have the same indexes too. You don't really gain much, other than semantically separating the index and avoiding saying `$a[$index]` when you already have it (it's `$value`). – cHao Apr 26 '12 at 02:33
4

array_combine() will merge your 2 arrays into one with key=>value pairs and then access them through foreach statement e.g

foreach(array_combine($a,$b) as $key=>$value) {
    echo $key."<br/>".$value;
}
Bhavesh G
  • 3,000
  • 4
  • 39
  • 66
dhoom
  • 49
  • 1
2

The answer depends on what exactly you need to do with the arrays and how you need to do it.

If your arrays have similar indexes, and you need to use the same element from each array, you could do like

foreach ($array1 as $index => $value1) {
    $value2 = $array2[$index];
    // do stuff with $value1 and $value2 here
}

(Although in this case, particularly if you find yourself doing this a lot, you may want to think about using a single array of either objects or arrays, so that the data will always be together and easier to connect.)

Or, if the arrays have the same type of elements in it and you want to iterate over both in order, you could iterate over array_merge($array1, $array2). (If the arrays aren't numerically indexed, though, and particularly if they have the same stringy keys, one of the arrays' elements could replace the other. See the docs on array_merge for details.)

There are a bunch of other possibilities, depending on how you need the elements. (The question really doesn't provide any info on that.)

cHao
  • 84,970
  • 20
  • 145
  • 172
1

Full Code:

1)

<?php
$First = array('a', 'b', 'c', 'd');
$Second = array('1', '2', '3', '4');

foreach($First as $indx => $value) {
    echo $First[$indx].$Second[$indx];
    echo "<br />";
}
?>

or 2)

<?php
$First = array('a', 'b', 'c', 'd');
$Second = array('1', '2', '3', '4');

for ($indx = 0 ; $indx < count($First); $indx ++) {
  echo $First[$indx] . $Second[$indx];
  echo "<br />";
}
?>
T.Todua
  • 53,146
  • 19
  • 236
  • 237