foreach only iterates over one iterator and offers one key and one value. How iterators are defined in PHP.
In your question, you write that you need several values ββ(but not keys, but I think it wonβt hurt). This does not work out of the box.
However, you can create an iterator that allows you to iterate over multiple iterators at the same time. The base class comes with PHP called MultipleIterator . Then you can create your own ForEachMultipleArrayIterator , which allows you to easily specify several keys and values ββfor each iteration:
$a = array(1,2,3); $b = array('b0' => 'a', 'b1' => 'b', 'b2' => 'c'); $c = array('c0' => 'x', 'c1' => 'y', 'c2' => 'z'); $it = new ForEachMultipleArrayIterator( // array keyvar valuevar array($a, 'akey' => 'avalue'), array($b, 'bkey' => 'bvalue'), array($c, 'ckey' => 'cvalue') ); foreach($it as $vars) { extract($vars); echo "$akey=$avalue, $bkey=$bvalue and $ckey=$cvalue \n"; } class ForEachMultipleArrayIterator extends MultipleIterator { private $vars; public function __construct() { parent::__construct(); $arrays = func_get_args(); foreach($arrays as $set) { if (count($set) != 2) throw new invalidArgumentException('Not well defined.'); $array = array_shift($set); if (!is_array($array)) throw new InvalidArgumentException('Not an array.'); $this->vars[key($set)] = current($set); parent::attachIterator(new ArrayIterator($array)); } } public function current() { return array_combine(array_keys($this->vars), parent::key()) + array_combine($this->vars, parent::current()); } }
Demo - But if you have come this far, I'm sure itβs clear that what you want to do can be solved much easier by actually sorting out something else. The example above is basically the same:
foreach(array_map(NULL, array_keys($a), $a, array_keys($b), $b, array_keys($c), $c) as $v) { list($akey, $avalue, $bkey, $bvalue, $ckey, $cvalue) = $v; echo "$akey=$avalue, $bkey=$bvalue and $ckey=$cvalue \n"; }
Itβs better to have your arrays in the correct order and then process them :)
See also: Multiple index variables in PHP foreach loop .