foreach
does only the iteration over one iterator and offering one key and one value. That's how iterators are defined in PHP.
In your question you write that you need multiple values (but not keys, but I think this 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 once. A base class ships with PHP it's called MultipleIterator
. You can then create your own ForEachMultipleArrayIterator
that allows you to easily specify multiple keys and values per 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've come that far, I'm pretty sure it's clear that what you want to do can be solved much easier by actually iterating over something else. The example above is basically the same as:
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";
}
So better get your arrays into the right order and then process them :)
See also: Multiple index variables in PHP foreach loop.