I have 2 arrays
$arr1 = array(1,3);
$arr2 = array(2,4);
I want merge them to one array with structure:
$arr = array(1,2,3,4);
Has php functions for that or exist good solution?
UPD: i don't need sort values, i want put elements from first array to odd positions, elements from second to even positions
You would have to merge them first, then sort them:
$arr = array_merge($arr1, $arr2);
sort($arr);
There is no built-in function to do what you are describing, assuming they are both the same length:
$len = count($arr1);
for($x=0; $x < $len; $x++) {
array_push($arr, $arr1[$x], $arr2[$x]);
}
$new_arr = array_merge($arr1, $arr2)
No. Php does not have a function for this that I know of. You'll have to write your own, but it's very simple.
Pseudocode:
cmb = []
for (i=0, i<arr1.length, i++) {
array_push(cmb, arr1[i]);
array_push(cmb, arr2[i]);
}
Related
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.
Is there a straightforward way in PHP to combine multiple arrays together but respect the relative order of the elements?
So for example if I had two arrays
$x = ('1','2','3','4');
and
$y = array('a','b','c','d','e');
and I wanted combine them into a single array
$z = ('1','a','2','b','3','c','4','d','e');
Is there a straightforward way of doing this? The ideal solution would also account for different lengths of arrays, behaving as my example does.
array_merge doesn't seem to achieve what I want as it just appends one array to the other.
My current solution loops through each array in order and pushes values to my $z array. This is not only inelegant, it also requires the input arrays to have the same number of values, which isn't ideal for my application.
Any insight would be appreciated
I think this should work -
$count = max(count($x), count($y));
$newArr = array();
for ($i = 0; $i < $count; $i++) {
// enter values to the new array based on key
foreach(array($x, $y) as $arr) {
if (isset($arr[$i])) {
$newArr[] = $arr[$i];
}
}
}
var_dump($newArr);
You could use this generic function, which can accept any number of arrays, and will output an array with the elements taken from the first "column" first, then from the second, etc:
function mix_merge(...$args) {
return call_user_func_array('array_merge',
array_map(function($i) use ($args) { return array_column($args, $i); },
range(0, max(array_map('count', $args))-1)));
}
// Sample data:
$x = array('1','2','3','4');
$y = array('a','b','c','d','e');
$z = array('A','B','C');
$res = mix_merge($x, $y, $z);
Result array will be:
['1', 'a', 'A', '2', 'b', 'B', '3', 'c', 'C', '4', 'd', 'e']
Iterate from 0 to the greater length of the two arrays.
At each step, if array $x contains item at index, push it to final array $z. Do the same for array $y.
You can also try this
$x = array('1','2','3','4');
$y = array('a','b','c','d','e');
foreach($y as $key=>$value){
if($x[$key]){
$z[] = $x[$key];
$z[] = $value;
}else {
$z[] = $value;
}
}
This question already has answers here:
Combining php arrays
(3 answers)
Closed 7 years ago.
I have two arrays:
$arr1= array("A","B","C");
$arr2= array("1","2","3");
Output i need as:
$arr3= array("A","1","B","2","C","3");
Can anyone help please?
If your first two arrays has the same length, you can use a loop to get the array you want:
<?PHP
$arr1= array("A","B","C");
$arr2= array("1","2","3");
$arr3=[];
for($i = 0; $i < count($arr1); $i++)
array_push($arr3, $arr1[$i], $arr2[$i]);
?>
It will return:
$arr3= array("A","1","B","2","C","3");
Take a look at array_merge()
array_merge ( array $array1 [, array $... ] )
Merges the elements of one or more arrays together so that the values
of one are appended to the end of the previous one. It returns the
resulting array.
If the input arrays have the same string keys, then the later value
for that key will overwrite the previous one. If, however, the arrays
contain numeric keys, the later value will not overwrite the original
value, but will be appended.
This will work to combine the two arrays together:
$output = $array1 + $array2;
This snippet could solve what you asked, also if arrays are not equal in length.
function array_interpolation($arr1, $arr2) {
$result = array();
$len1 = count($arr1);
$len2 = count($arr2);
$maxlen = max($len1, $len2);
for($i = 0; $i < $maxlen; $i++) {
if($i < $len1) {
array_push($result, $arr1[$i]);
}
if($i < $len2) {
array_push($result, $arr2[$i]);
}
}
return $result;
}
I want to find out the maximum value of the each key in the array
$arr1= array(
0=>array(1,2,3),
1=>array(2,4,6),
2=>array(25,4,5));
}
I want to find the maximum value for each value for the corresponding key
The final output shuld be
$max_array = array(25,4,6);
with the below code i get error max(): When only one parameter is given, it must be an array in
foreach ($res_arr as $k=>$subArray) {
foreach ($subArray as $id=>$value) {
$spanmaxArray[$id] = max($value);
}
}
First, rotate array to makes columns as lines
$arr1= array(
0=>array(1,2,3),
1=>array(2,4,6),
2=>array(25,4,5)
);
$arr2 = array();
foreach($arr1 as $subArray) {
foreach($subArray as $k=>$v) {
$arr2[$k][] = $v;
}
}
Then, use array_map as #HamZa did
$max_array = array_map('max', $arr2);
print_r($max_array);
foreach ($res_arr as $k=>$subArray){
$max = 0;
foreach ($subArray as $id=>$value){
if ($value>$max){
$max = $value;
}
}
$spanmaxArray[$k] = $max;
}
Try this.
Definitely the shortest version:
$max_array = array_map('max', $arr1);
array_map() takes each element array of $arr1 and applies max() to it.
Edited after seeing that max in each column position is desired:
$sorted = array();
for ($i = 0; $i <=2; $i++) {
$sorted[$i] = array_column($input, $i);
}
This loops over the array and applies array_column() to each (requires PHP 5.5).
So:
$sorted = array();
for ($i = 0; $i <=2; $i++) {
$sorted[$i] = array_column($arr1, $i);
}
$max_array = array_map('max', $sorted);
working version
You only need one loop, because the max function takes an array as a parameter. But the answer you are giving is wrong, unless I've misunderstood the problem.
I think what you're after is:
$max_array = array_map('max', $arr1);
All of the earlier answers are working too hard.
Use array_map() as the iterating function.
Unpack your multidimensional array with the "spread/splat operator" (...); in other words, convert your single array containing three subarrays into three separate arrays.
Call max() on the three elements as they are synchronously iterated by array_map().
Code: (Demo)
$arr1 = [
[1, 2, 3],
[2, 4, 6],
[25, 4, 5],
];
var_export(array_map('max', ...$arr1));
The above is a more versatile and concise version of the following one-liner which has the same effect on the sample array:
var_export(array_map('max', $arr1[0], $arr1[1], $arr1[2]));
Output:
array (
0 => 25,
1 => 4,
2 => 6,
)
*A note for researchers: if processing a multidimensional array that has associative first level keys, you will need to index the first level so that the splat operator doesn't choke on the keys.
...array_values($array)
What's an efficient way to pop the last n elements in an array?
Here's one:
$arr = range(1,10);
$n = 2;
$popped_array = array();
for ($i=0; $i < $n; $i++) {
$popped_array[] = array_pop($arr);
}
print_r($popped_array); // returns array(10,9);
Is there a more efficient way?
Use array_splice():
If you're trying to remove the last n elements, use the following function:
function array_pop_n(array $arr, $n) {
return array_splice($arr, 0, -$n);
}
Demo
If you want to retrieve only the last n elements, then you can use the following function:
function array_pop_n(array $arr, $n) {
array_splice($arr,0,-$n);
return $arr;
}
Demo
It's important to note, looking at the other answers, that array_slice will leave the original array alone, so it will still contain the elements at the end, and array_splice will mutate the original array, removing the elements at the beginning (though in the example given, the function creates a copy, so the original array still would contain all elements). If you want something that literally mimics array_pop (and you don't require the order to be reversed, as it is in your OP), then do the following.
$arr = range(1, 10);
$n = 2;
$popped_array = array_slice($arr, -$n);
$arr = array_slice($arr, 0, -$n);
print_r($popped_array); // returns array(9,10);
print_r($arr); // returns array(1,2,3,4,5,6,7,8);
If you require $popped_array to be reversed, array_reverse it, or just pop it like your original example, it's efficient enough as is and much more direct.
Why not use array_slice. You can give a start and a length, so if you do 2 from the end you will get the last two items in the array:
$arr = range(1,10);
$n = 2;
$start = count($arr) - $n;
print_r(array_slice($arr, $start, $n));
Thanks for the array_slice comments. I don't know why that didn't immediately come to mind.
It looks (to me) like the easiest way is:
$arr = range(1,10);
$n = 2;
$popped_array = array_slice($arr,-$n);
print_r($popped_array); // returns array(10,9);
I have 2 arrays, the value will be loaded from database, below is an example:
$arr1 = array(1,2,3);
$arr2 = array(1,2,3,4,5,6,7);
What I want to do is to check if all the values in $arr1 exist in $arr2. The above example should be a TRUE while:
$arr3 = array(1,2,4,5,6,7);
comparing $arr1 with $arr3 will return a FALSE.
Normally I use in_array because I only need to check single value into an array. But in this case, in_array cannot be used. I'd like to see if there is a simple way to do the checking with a minimum looping.
UPDATE for clarification.
First array will be a set that contains unique values. Second array can contain duplicated values. They are both guaranteed an array before processing.
Use array_diff():
$arr1 = array(1,2,3);
$arr2 = array(1,2,3,4,5,6,7);
$arr3 = array_diff($arr1, $arr2);
if (count($arr3) == 0) {
// all of $arr1 is in $arr2
}
You can use array_intersect or array_diff:
$arr1 = array(1,2,3);
$arr2 = array(1,2,3,4,5,6,7);
if ( $arr1 == array_intersect($arr1, $arr2) ) {
// All elements of arr1 are in arr2
}
However, if you don't need to use the result of the intersection (which seems to be your case), it is more space and time efficient to use array_diff:
$arr1 = array(1,2,3);
$arr2 = array(1,2,3,4,5,6,7);
$diff = array_diff($arr1, $arr2);
if ( empty($diff) ) {
// All elements of arr1 are in arr2
}
You can try use the array_diff() function to find the difference between the two arrays, this might help you. I think to clarify you mean, all the values in the first array must be in the second array, but not the other way around.
In my particular case I needed to check if a pair of ids was processed before or not. So simple array_diff() did not work for me.
Instead I generated keys from ids sorted alphabetically and used them with in_array:
<?php
$pairs = array();
// ...
$pair = array($currentId, $id);
sort($pair);
$pair = implode('-', $pair);
if (in_array($pair, $pairs)) {
continue;
}
$pairs[$pair] = $pair;
This is probably not an optimum solution at all but I just needed it for a dirty script to be executed once.