0

I have n arrays (for example 2 arrays):

$tab['1'] = array('1', '2', '3');
$tab['2'] = array('A', 'B', 'C');

How can i get this result?

1 A
1 B
1 C
2 A
2 B
2 C
3 A
3 B
3 C

That is, each element from first array with each element from other arrays.

4
  • PHP does not support the syntax you used. Commented Apr 9, 2012 at 20:28
  • This looks like homework. What have you tried? Commented Apr 9, 2012 at 20:30
  • On the first look you'd assume a function called array_product does this. But on a second look you notice that it actually multiplies the number of the array. Bleh, PHP. Because you have to multiply all elements in an array that often! Commented Apr 9, 2012 at 20:32
  • Im sorry i was writing fast. I have change code. Commented Apr 9, 2012 at 20:33

3 Answers 3

5

You would do a 2-dimensional iteration.

Run through the first array like this

foreach ($tab[1] as $number) {...}

For each number in the first array, the code in the brackets will be executed. If you want to count each letter for each number, just repeat the same iteration inside:

foreach ($tab[1] as $number) {
    foreach ($tab[2] as $letter) {
        print($number.' '.$letter."\n");
    }
}
0
3
foreach ($tab[1] as $num) {
   foreach ($tab[2] as $letter) {
      echo "$num $letter\n";
   }
}
0

Another way to do it (for the fun of it)

array_map(function($a, $b) {
             foreach( $b as $e ) {
                 echo "$a $e\n";
             }
          }, 
          $tab['1'], 
          array_fill(0, count($tab['1']), $tab['2']));

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.