I want to extend two array in single foreach loop like ..
$array=array(1,2,3,4,5,6,7,);
$array2=array(1=>'b','2=>c',3=>'d',4=>'e',5=>'f',6=>'g',7=>'x');
foreach($array as first && $aaray2 as second){
echo first;
echo second;
}
Is it possible? how I call indexes of each array and values of each array
Since your arrays don't use named keys you can reuse the array key. If you use named keys this only works if the keys are the same.
foreach ($array as $key => $value) {
echo $value;
echo $array2[$key];
}
You could also use a for loop counting from 0 to the array length since php automatically uses numbers as keys if you don't specify any, but the above solution is probably more readable and will work with named keys.
You can use array_combine to create one array with key=>value pairs.
foreach(array_combine($array, $array2) as $key => $value){
echo $key;
echo $value;
}
(array_combine returns the combined array, FALSE if the number of elements for each array isn't equal)
You can use two for loops like this:
foreach($array as $arr) {
echo $arr;
for($i=1; $i<count($array2); $i++){
echo $array2[$i];
}
}
Just merge two array and do loop
$array=array(1,2,3,4,5,6,7,);
$array2=array('b','c','d','e','f','g','x');
$array = array_merge($array, $array2);
foreach ($array as $value) {
echo $value;
}
The other day I wrote a ZipIterator
class which is designed to do exactly this.
Usage example:
$array=array(1,2,3,4,5,6,7,);
$array2=array('b','c','d','e','f','g','x');
foreach (new ZipIterator($array, $array2) as $pair) {
echo "first: ".$pair[0].", second: ".$pair[1];
}
Features:
Requirements:
See it in action and grab the source from GitHub.
$array=array(1,2,3,4,5,6,7,);
$array2=array('b','c','d','e','f','g','x');
$mi = new MultipleIterator(
MultipleIterator::MIT_NEED_ALL | MultipleIterator::MIT_KEYS_ASSOC
);
$mi->attachIterator(new ArrayIterator($array), 'val');
$mi->attachIterator(new ArrayIterator($array2), 'val2');
foreach($mi as $details) {
echo $details['val'], ' - ', $details['val2'], PHP_EOL;
}
or
$array=array(1,2,3,4,5,6,7,);
$array2=array('b','c','d','e','f','g','x');
$mi = new MultipleIterator(
MultipleIterator::MIT_NEED_ALL | MultipleIterator::MIT_KEYS_ASSOC
);
$mi->attachIterator(new ArrayIterator($array), 'val');
$mi->attachIterator(new ArrayIterator($array2), 'val2');
foreach($mi as $details) {
extract($details);
echo $val, ' - ', $val2, PHP_EOL;
}
or for PHP 5.5+ only
$array=array(1,2,3,4,5,6,7,);
$array2=array('b','c','d','e','f','g','x');
$mi = new MultipleIterator(
MultipleIterator::MIT_NEED_ALL | MultipleIterator::MIT_KEYS_ASSOC
);
$mi->attachIterator(new ArrayIterator($array));
$mi->attachIterator(new ArrayIterator($array2));
foreach($mi as list($val, $val2)) {
echo $val, ' - ', $val2, PHP_EOL;
}