This question already has answers here:
Two arrays in foreach loop
(24 answers)
Closed 7 years ago.
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
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];
}
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;
}
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.)
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 />";
}
?>
Related
since I've tried different things - like for/while-loops, I finally ended up here. What I'm trying to do is to merge different x arrays (from a form) into one array, so that I can count the answers. My code for merging actually looks like this:
foreach($_POST as $key =>$value){
foreach ($value as $answer){
echo $answer."<br />";
}
$tmp+=1;
$data[$key] = $value;
}
$results = array_merge($data['q1'], $data['q2']);
I'd like to input the content of array_merge based on how many questions (q1, q2, ...) are in the form. So I tried this:
$array_loop = array();
for ($k = 1 ; $k < $tmp; $k++) {
$array_loop.='$data["q' . $k . '"], ';
};
Of course, it's not working because it's an array so string conversion. Any hints?
you can use
$result = array_merge(...$array_loop);
to save multiple arrays into one array
I need help regarding a foreach() loop. aCan I pass two variables into one foreach loop?
For example,
foreach($specs as $name, $material as $mat)
{
echo $name;
echo $mat;
}
Here, $specs and $material are nothing but an array in which I am storing some specification and material name and want to print them one by one. I am getting the following error after running:
Parse error: syntax error, unexpected ',', expecting ')' on foreach line.
In the Beginning, was the For Loop:
$n = sizeof($name);
for ($i=0; i < $n; $i++) {
echo $name[$i];
echo $mat[$i];
}
You can not have two arrays in a foreach loop like that, but you can use array_combine to combine an array and later just print it out:
$arraye = array_combine($name, $material);
foreach ($arraye as $k=> $a) {
echo $k. ' '. $a ;
}
Output:
first 112
second 332
But if any of the names don't have material then you must have an empty/null value in it, otherwise there is no way that you can sure which material belongs to which name. So I think you should have an array like:
$name = array('amy','john','morris','rahul');
$material = array('1w','4fr',null,'ff');
Now you can just
if (count($name) == count($material)) {
for ($i=0; $i < $count($name); $i++) {
echo $name[$i];
echo $material[$i];
}
Just FYI: If you want to have multiple arrays in foreach, you can use list:
foreach ($array as list($arr1, $arr2)) {...}
Though first you need to do this: $array = array($specs,$material)
<?php
$abc = array('first','second');
$add = array('112','332');
$array = array($abc,$add);
foreach ($array as list($arr1, $arr2)) {
echo $arr1;
echo $arr2;
}
The output will be:
first
second
112
332
And still I don't think it will serve your exact purpose, because it goes through the first array and then the second array.
You can use the MultipleIterator of SPL. It's a bit verbose for this simple use case, but works well with all edge cases:
$iterator = new MultipleIterator();
$iterator->attachIterator(new ArrayIterator($specs));
$iterator->attachIterator(new ArrayIterator($material));
foreach ($iterator as $current) {
$name = $current[0];
$mat = $current[1];
}
The default settings of the iterator are that it stops as soon as one of the arrays has no more elements and that you can access the current elements with a numeric key, in the order that the iterators have been attached ($current[0] and $current[1]).
Examples for the different settings can be found in the constructor documentation.
This is one of the ways to do this:
foreach ($specs as $k => $name) {
assert(isset($material[$k]));
$mat = $material[$k];
}
If you have ['foo', 'bar'] and [2 => 'mat1', 3 => 'mat2'] then this approach won't work but you can use array_values to discard keys first.
Another apprach would be (which is very close to what you wanted, in fact):
while ((list($name) = each($specs)) && (list($mat) = each($material))) {
}
This will terminate when one of them ends and will work if they are not indexed the same. However, if they are supposed to be indexed the same then perhaps the solution above is better. Hard to say in general.
Do it using a for loop...
Check it below:
<?php
$specs = array('a', 'b', 'c', 'd');
$material = array('x', 'y', 'z');
$count = count($specs) > count($material) ? count($specs) : count($material);
for ($i=0;$i<$count;$i++ )
{
if (isset($specs[$i]))
echo $specs[$i];
if (isset($material[$i]))
echo $material[$i];
}
?>
OUTPUT
axbyczd
Simply use a for loop. And inside that loop, extract values of your array:
For (I=0 to 100) {
Echo array1[i];
Echo array2[i]
}
foreach (($_POST['pedimento'] as $value) && ($_POST['observacion'] as $obs))
{
$sql1=mysql_query("INSERT INTO pedimento (`error`,`observacion`) VALUES ('$value','$obs')");
}
im trying to insert data from two arrays, does anyone know how can i get the data from the two arrays simultaneously, and save them together in one sql statement?
I would turn your foreach into a for loop with an int counter:
for($i = 0; $i < array.length; $i++)
{
$x = arrayOne[$i];
$y = arrayTwo[$i];
$sql1=mysql_query("INSERT INTO pedimento (error,observacion) VALUES ('$x','$y')"); }
}
PHP isn't my strong suit (not by a long shot) but I checked that For loops work. As long as array logic works even remotely like other languages, the above statement should loop through both arrays (assuming they are the same length) and create an INSERT statement with the two values it finds.
Do not use $_POST values in a query like this! Move to prepared statements using PDO or MySQLi.
The only way this makes sense as the other answers assume, is if the arrays are the same length and have identical keys so:
foreach ($_POST['pedimento'] as $key => $value)
{
$obs = $_POST['observacion'][$key];
$sql1 = mysql_query("INSERT INTO pedimento (`error`,`observacion`)
VALUES ('$value','$obs')");
}
foreach (array_combine($_POST['pedimento'], $_POST['observacion']) as $value => $val) {
echo $value;
echo $val;
}
what about this?
$array1 = array("A","B","C");
$array2 = array(1,2,3);
foreach (array_combine($array1,$array2) as $first => $second) {
echo $first." ". $second;
}
output:
A 1B 2C 3
This question already has answers here:
php looping through multiple arrays [duplicate]
(8 answers)
Closed 9 years ago.
How can I iterate through two arrays at the same time that have equal sizes ?
for example , first array $a = array( 1,2,3,4,5);
second array $b = array(1,2,3,4,5);
The result that I would like through iterating through both is having the looping process going through the same values to produce a result like
1-1
2-2
3-3
4-4
5-5
I tried to do it this way below but it didn't work , it keeps going through the first loop again
foreach($a as $content) {
foreach($b as $contentb){
echo $a."-".$b."<br />";
}
}
Not the most efficient, but a demonstration of SPL's multipleIterator
$mi = new MultipleIterator();
$mi->attachIterator(new ArrayIterator($a));
$mi->attachIterator(new ArrayIterator($b));
$newArray = array();
foreach ( $mi as $value ) {
list($value1, $value2) = $value;
echo $value1 , '-' , $value2 , PHP_EOL;
}
Use a normal for loop instead of a foreach, so that you get an explicit loop counter:
for($i=0; $i<count($content)-1; $i++) {
echo $content[$i].'-'.$contentb[$i];
}
If you want to use string based indexed arrays, and know that the string indexes are equal between arrays, you can stick with the foreach construct
foreach($content as $key=>$item) {
echo $item.'-'.$contentb[$key];
}
If they're the same size, just do this:
foreach($a as $key => $content){
$contentb = $b[$key];
echo($content."-".$contentb."<br />");
}
I would like to reverse the order of this code's list items. Basically it's a set of years going from oldest to recent and I am trying to reverse that output.
<?php
$j=1;
foreach ( $skills_nav as $skill ) {
$a = '<li><a href="#" data-filter=".'.$skill->slug.'">';
$a .= $skill->name;
$a .= '</a></li>';
echo $a;
echo "\n";
$j++;
}
?>
Walking Backwards
If you're looking for a purely PHP solution, you can also simply count backwards through the list, access it front-to-back:
$accounts = Array(
'#jonathansampson',
'#f12devtools',
'#ieanswers'
);
$index = count($accounts);
while($index) {
echo sprintf("<li>%s</li>", $accounts[--$index]);
}
The above sets $index to the total number of elements, and then begins accessing them back-to-front, reducing the index value for the next iteration.
Reversing the Array
You could also leverage the array_reverse function to invert the values of your array, allowing you to access them in reverse order:
$accounts = Array(
'#jonathansampson',
'#f12devtools',
'#ieanswers'
);
foreach ( array_reverse($accounts) as $account ) {
echo sprintf("<li>%s</li>", $account);
}
Or you could use the array_reverse function.
array_reverse() does not alter the source array, but returns a new array. (See array_reverse().) So you either need to store the new array first or just use function within the declaration of your for loop.
<?php
$input = array('a', 'b', 'c');
foreach (array_reverse($input) as $value) {
echo $value."\n";
}
?>
The output will be:
c
b
a
So, to address to OP, the code becomes:
<?php
$j=1;
foreach ( array_reverse($skills_nav) as $skill ) {
$a = '<li><a href="#" data-filter=".'.$skill->slug.'">';
$a .= $skill->name;
$a .= '</a></li>';
echo $a;
echo "\n";
$j++;
}
Lastly, I'm going to guess that the $j was either a counter used in an initial attempt to get a reverse walk of $skills_nav, or a way to count the $skills_nav array. If the former, it should be removed now that you have the correct solution. If the latter, it can be replaced, outside of the loop, with a $j = count($skills_nav).
If you don't mind destroying the array (or a temp copy of it) you can do:
$stack = array("orange", "banana", "apple", "raspberry");
while ($fruit = array_pop($stack)){
echo $fruit . "\n<br>";
}
produces:
raspberry
apple
banana
orange
I think this solution reads cleaner than fiddling with an index and you are less likely to introduce index handling mistakes, but the problem with it is that your code will likely take slightly longer to run if you have to create a temporary copy of the array first.
Fiddling with an index is likely to run faster, and it may also come in handy if you actually need to reference the index, as in:
$stack = array("orange", "banana", "apple", "raspberry");
$index = count($stack) - 1;
while($index > -1){
echo $stack[$index] ." is in position ". $index . "\n<br>";
$index--;
}
But as you can see, you have to be very careful with the index...
You can use usort function to create own sorting rules
Assuming you just need to reverse an indexed array (not associative or multidimensional) a simple for loop would suffice:
$fruits = ['bananas', 'apples', 'pears'];
for($i = count($fruits)-1; $i >= 0; $i--) {
echo $fruits[$i] . '<br>';
}
If your array is populated through an SQL Query consider reversing the result in MySQL, ie :
SELECT * FROM model_input order by creation_date desc
If you do not have Boolean false values in your array, you could use next code based on internal pointer functions:
$array = ['banana', 'apple', 'pineapple', 'lemon'];
$value = end($array);
while ($value !== false) {
// In case you need a key
$key = key($array);
// Do something you need to
echo $key . ' => ' . $value . "\n";
// Move pointer
$value = prev($array);
}
This solution works for associative arrays with arbitrary keys and do not require altering existing or creating a new one.
<?php
$j=1;
array_reverse($skills_nav);
foreach ( $skills_nav as $skill ) {
$a = '<li><a href="#" data-filter=".'.$skill->slug.'">';
$a .= $skill->name;
$a .= '</a></li>';
echo $a;
echo "\n";
$j++;
}
?>