If i have two arrays
$arr1 = array(1,2,3,4,5,6,7,8,9,10,11); // 11 values
$arr2 = array('m1','m2','m3','m4','m5'); // 5 values
it is clear they have different number of values
and i want to use foreach() to print out as follow
1-m1
2-m2
3-m3
4-m4
5-m5
6-m1 <--- it start pick from $arr2
7-m2
8-m3
9-m4
10-m5
11-m1 <--- it start pick from $arr2
each value from $arr1 will pick value of same key from arr2 till arr2 ends then will repick from the start of $arr2 and so on
This is fairly simple logic.
Define a variable ($key) outside of your loop (starting at 0 because array indexes start at 0), and create a variable ($arr2_max) to hold the max amount of values in $arr2.
On each loop, check if $key is equal to the max amount of values in $arr2, if it is, set $key back to 0. Also increment $key by 1 at the end of each loop.
$arr1 = array(1,2,3,4,5,6,7,8,9,10,11); // 11 values
$arr2 = array('m1','m2','m3','m4','m5'); // 5 values
$key = 0;
$arr2_max = count($arr2);
foreach($arr1 as $arr1_val) {
if($key == $arr2_max) $key = 0;
$arr2_val = $arr2[$key]; //this is the value from $arr2
echo "$arr1_val-$arr2_val<br>";
$key++;
}
Output:
1-m1
2-m2
3-m3
4-m4
5-m5
6-m1
7-m2
8-m3
9-m4
10-m5
11-m1
If your $arr2 is not numerically indexed, first use array_values() to make it numerically indexed. $arr2 = array_values($arr2);
You could just do a simple modulus operation to reset index back to zero on reaching size of $arr2.
<?php
$arr1 = array(1,2,3,4,5,6,7,8,9,10,11); // 11 values
$arr2 = array('m1','m2','m3','m4','m5'); // 5 values
$size = count($arr2);
foreach($arr1 as $index => $curr){
echo $curr,"-",$arr2[$index % $size],PHP_EOL;
}
Demo: https://3v4l.org/R6u2q
Update:
For arrays with non numerical keys, you could just do:
<?php
$arr1 = array(1,2,3,4,5,6,7,8,9,10,11); // 11 values
$arr2 = array('m1','m2','m3','m4','m5'); // 5 values
$values = array_values($arr2);
$size = count($arr2);
foreach($arr1 as $index => $curr){
echo $curr,"-",$values[$index % $size],PHP_EOL;
}
Related
I have a code like this:
Lets assume that this arrays has this values:
$arr1 = array();
$arr2 = array();
$result = array();
$arr1[] = array( 'grade' => [1,2,3,4] );
$arr2[] = array( 'grade' => [1,2,3,4] );
foreach($arr1 as $a1){
$set1 = $a1['grade'];
foreach($arr2 as $a2){
$set2 = $a2['grade'];
}
$result[] = array('show_result' => $set1+$set2);
}
foreach{$result as $res){
echo $res['show_result'];
}
The output of the array $res['show_result'] must be:
2, 4, 6, 8
But I get the wrong addition of this arrays. Help will be much appreciated.
As Joni said, your first error is on line 3: ' should be ;
Then, you're not filling arrays like you wanted : array( 'grade' => 1,2,3,4 ); creates an array with first key is 'grade' with value '1', then second key is '0' with value '2' etc...
Your last foreach loop has a syntax error similar to your first error.
See a working correction here
$arr1 = array();
$arr2 = array();
$result = array();
array_push($arr1, 1, 2, 3, 4); //fill array with 4 values (integers)
array_push($arr2, 1, 2, 3, 4); //fill array with 4 values (integers)
//so $arr1 & $arr2 are now a 4 elements arrays
$length = count($arr1); //size of array, here 4
for ($i = 0; $i < $length; $i++) { //loop over arrays
array_push($result, ($arr1[$i] + $arr2[$i])); //fill the results array with sum of the values from the same position
}
var_dump($result);
You have quite a few syntax errors in your code.
Although this solution works, the idea behind using the same counter, $i, to extract a value from both arrays is brittle. For example, you'll get an Undefined offset if the first array has 5 grades instead of 4. If you take a step back and explain your problem in the larger context, perhaps we can provide a better solution. I get the sneaking suspicion you're asking an XY Problem.
http://sandbox.onlinephpfunctions.com/code/bb4f492c183fcde1cf4edd50de7ceebf19fe343a
<?php
$gradeList1 = ['grade' => [1,2,3,4]];
$gradeList2 = ['grade' => [1,2,3,4]];
$result = [];
for ($i = 0; $i < count($gradeList1['grade']); $i++) {
$first = $gradeList1['grade'][$i];
$second = $gradeList2['grade'][$i];
$result['show_result'][] = (int)$first + (int)$second;
}
var_dump($result);
This question already has answers here:
Transpose and flatten two-dimensional indexed array where rows may not be of equal length
(4 answers)
Closed 5 months ago.
There are two arrays , the second array will always be smaller by 1 from first array. The first array contains the numbers and second array contains the mathematical operators.
$arr1 = [210,11,12];
$arr2 = ['-','/'];
the code which i have written is working on this test case only ,but when i increase the number of elements in it. It fails.
$arr1 = [210,11,12,12];
$arr2 = ['-','/','/'];
the code i have tried so far..
$arr1 = [210,11,12];
$arr2 = ['-','/'];
$arr3 = [];
for($i=0;$i<count($arr1);$i++){
if($i == 0){
$arr3[] = $arr1[0];
}
if ($i % 2 != 0) {
$arr3[] = $arr1[$i];
}
else {
if($i < (count($arr2)-1)){
$arr3[] = $arr2[$i];
}else{
$arr3[] = $arr2[$i-1];
}
}
}
array_push($arr3,end($arr1));
print_r($arr3);
the expected result will be
$arr3 = [210,'-',11,'/','12','/','12']
You can mix the two arrays together by converting columns to rows with array_map, then merging the rows.
$arr3 = array_merge(...array_map(null, $arr1, $arr2));
array_pop($arr3);
The array_map(null, $arr1, $arr2) expression will result in
[[210, '/'], [11, '/'], [12, '/'], [12, null]]
then, array_merge(...) combines all the inner arrays together into one for the final result.
array_pop will remove the trailing null which is there because of the uneven size of the two arrays, but if you're going to end up imploding this and outputting the results as a math expression, you don't need to do it since that won't show up anyway. In fact, if that is the goal you can just add the implode directly to the expression above.
echo implode(' ', array_merge(...array_map(null, $arr1, $arr2)));
Loop the first array and use $key =>.
Then you build the new array in the loop and if $arr2 has a value with the same key, add it after the $arr1 value.
$arr1 = [210,11,12,12];
$arr2 = ['-','/','/'];
foreach($arr1 as $key => $val){
$arr3[] = $val;
if(isset($arr2[$key])) $arr3[] = $arr2[$key];
}
var_dump($arr3);
//[210, -, 11, /, 12, /, 12]
Provided, as you say, that the second array is always larger by one element, then this would be a simple way to do it:
function foo(array $p, array $q): array {
$r = [array_shift($p)];
foreach ($q as $x) {
$r[] = $x;
$r[] = array_shift($p);
}
return $r;
}
print_r(
foo([210,11,12], ['-', '/'])
);
print_r(
foo([210,11,12,12], ['-','/','/'])
);
https://3v4l.org/F0ud8
If the indices of the arrays are well formed, the above could be simplified to:
function foo(array $p, array $q): array {
$r = [$p[0]];
foreach ($q as $i => $x) {
$r[] = $x;
$r[] = $p[$i + 1];
}
return $r;
}
I wanted to offer a couple of approaches that do not modify the original array, accommodate the possibility of empty input arrays, and do not use more than one loop.
By prepopulating the result array with the first value from the numbers array, then iterating the operators array, you can avoid making iterated checks of isset().
Code: (Demo) (Demo without iterated array_push() calls)
$numbers = [210, 11, 12];
$operators = ['-', '/'];
$result = (array)($numbers[0] ?? []);
foreach ($operators as $i => $operator) {
array_push($result, $operator, $numbers[++$i]);
}
var_export($result);
or with array_reduce():
var_export(
array_reduce(
$operators,
function($result, $operator) use($numbers) {
static $i = 0;
array_push($result, $operator, $numbers[++$i]);
return $result;
},
(array)($numbers[0] ?? [])
)
);
I have 2 SELECT statement in my PHP. Both the select statements fetch data from two different DB. The fetched data is saved in PDO Assoc Array. The problem is when I want to compare those two arrays to find that if the column 'id' exist in both arrays or not. If it exists then ignore it. If it's a unique id then save it into a third array. But I found some problems in my Logic Below
And after running the below code I am getting a couple of error:
1: Array to string conversion
2: duplicate key value violates unique constraint
$arr1 = $msql->fetchAll(PDO::FETCH_ASSOC);
$array1 = array();
foreach($arr1 as $x){
$array1[] = $x['id'];
}
$arr2 = $psql->fetechAll(PDO::FETCH_ASSOC);
$array2 = array();
foreach($arr2 as $y){
$array2[] = $y['id'];
}
$finalarray = array();
for ($i = 0; $i < count($arr1); $i++){
if(count(array_intersect($array1,$array2)) <= 1){// is the count of id is 1 or less save that whole row in the $finalarray
$finalarray = $arr1[$i]; // saving the unique row.
}
else{
continue;
}
}
All I am trying to get the unique row of data array() after comparing their id column.
You can use in_array() function as both arrays are index array.
$finalarray = array();
for ($i = 0; $i < count($arr1); $i++){
if(count(array_intersect($array1,$array2)) <= 1){// is the count of id is 1 or less save that whole row in the $finalarray
$finalarray = $arr1[$i]; // saving the unique row.
}
else{
continue;
}
}
make change in code:
$finalarray = array();
for ($i = 0; $i < count($arr1); $i++){
if(!in_array($array1[$i], $array2)){
$finalarray[] = $array1[$i]; // saving the unique row.
}
}
You can simply use array_intersect() to get common values between two array. for difference, can use array_diff()
$array1 = [1,2,3,4,5,6,7];
$array2 = [2,4,6];
//array_intersect — Computes the intersection of arrays
$result = array_intersect($array1, $array2);
print_r($result);
//array_diff — Computes the difference of arrays
$result = array_diff($array1, $array2);
print_r($result);
DEMO
Rather than using 3 different arrays to get unique ids, you can do it by using one array. Make changes to your code as below:
$finalarray = array();
$arr1 = $msql->fetchAll(PDO::FETCH_ASSOC);
foreach($arr1 as $x){
if (!in_array($x['id'],$finalarray)) { // check id is already stored or not
$finalarray[] = $x['id'];
}
}
$arr2 = $psql->fetechAll(PDO::FETCH_ASSOC);
foreach($arr2 as $y){
if (!in_array($y['id'],$finalarray)) { // check id is already stored or not
$finalarray[] = $y['id'];
}
}
Maybe you should make sure which array is larger before your loop ;
Or using array_diff:
$finalarray = array_diff($array1 , $array2) ?? [];
$finalarray = array_merge( array_diff($array2 , $array1) ?? [], $finalarray );
Here I am Having an Issue:
I have two arrays like the following:
$array1 = array('1','2','1','3','1');
$array2 = array('1','2','3'); // Unique $array1 values
with array2 values i need all keys of an array1
Expected Output Is:
1 => 0,2,4
2 => 1
3 => 3
here it indicates array2 value =>array1 keys
Just use a loop:
$result = array();
foreach ($array1 as $index => $value) {
$result[$value][] = $index;
}
If you pass array_keys a 2nd parameter, it'll give you all the keys with that value.
So, just loop through $array2 and get the keys from $array1.
$result = array();
foreach($array2 as $val){
$result[$val] = array_keys($array1, $val);
}
The following code will do the job. It will create a result array in which the attribute val will contain the value that is searched in array and keys attribute will be an array that contains the found keys. Based on your values following is an example:
$array1 =array('1','2','1','3','1');
$array2 =array('1','2','3');
$results = array();
foreach ($array2 as $key2=>$val2) {
$result = array();
foreach ($array1 as $key1=>$val1 ) {
if ($val2 == $val1) {
array_push($result,$key1);
}
}
array_push($results,array("val"=>$val2,keys=>$result ));
}
echo json_encode($results);
The result will be:
[{"val":"1","keys":[0,2,4]},
{"val":"2","keys":[1]},
{"val":"3","keys":[3]}]
I have an array which I want to slice in 4 other arrays because I want to display the content of the first array on four columns.
I have tried the code above, but what I get is N columns with 4 items.
$groups = array();
for ($i = 0; $i < count($menu); $i += 4) $groups[] = array_slice($menu, $i, 4);
Can this be modified in order to get exactly 4 columns and distribute the values so they fit?
Like Michael Berkowski suggested:
$groups = array_chunk($menu,4);
Should give you what you need. If you're more into "manual labour":
$groups = array();
while($groups[] = array_splice($menu,0,4))
{//no need for any code here ^^ chunks the array just fine
printf('This loop will run another %d times<br/>',(int)ceil(count($menu)/4));
}
Update:
I see I got this a bit wrong... want to chunk into 4 arrays, not into arrays of four:
$groups = array_chunk($menu,(int)ceil(count($menu)/4));
You can try
// Some Random array
$array = range(1, 20);
// Split it 4 Chuncks
$array = array_chunk($array, 4);
// Slice The first 4 Chunks
$array = array_slice($array, 0, 4);
// Output Result
foreach ( $array as $set ) {
printf("<li>%s</li>", implode(",", $set));
}