PHP append a sub-array into another array [duplicate] - php

I have two arrays like this:
array(
'11' => '11',
'22' => '22',
'33' => '33',
'44' => '44'
);
array(
'44' => '44',
'55' => '55',
'66' => '66',
'77' => '77'
);
I want to combine these two array such that it does not contains duplicate and as well as keep their original keys. For example output should be:
array(
'11' => '11',
'22' => '22',
'33' => '33',
'44' => '44',
'55' => '55',
'66' => '66',
'77' => '77'
);
I have tried this but it is changing their original keys:
$output = array_unique( array_merge( $array1 , $array2 ) );
Any solution?

Just use:
$output = array_merge($array1, $array2);
That should solve it. Because you use string keys if one key occurs more than one time (like '44' in your example) one key will overwrite preceding ones with the same name. Because in your case they both have the same value anyway it doesn't matter and it will also remove duplicates.
Update: I just realised, that PHP treats the numeric string-keys as numbers (integers) and so will behave like this, what means, that it renumbers the keys too...
A workaround is to recreate the keys.
$output = array_combine($output, $output);
Update 2: I always forget, that there is also an operator (in bold, because this is really what you are looking for! :D)
$output = $array1 + $array2;
All of this can be seen in:
http://php.net/manual/en/function.array-merge.php

You should take to consideration that $array1 + $array2 != $array2 + $array1
$array1 = array(
'11' => 'x1',
'22' => 'x1'
);
$array2 = array(
'22' => 'x2',
'33' => 'x2'
);
with $array1 + $array2
$array1 + $array2 = array(
'11' => 'x1',
'22' => 'x1',
'33' => 'x2'
);
and with $array2 + $array1
$array2 + $array1 = array(
'11' => 'x1',
'22' => 'x2',
'33' => 'x2'
);

This works:
$output = $array1 + $array2;

The new way of doing it with php7.4 is Spread operator [...]
$parts = ['apple', 'pear'];
$fruits = ['banana', 'orange', ...$parts, 'watermelon'];
var_dump($fruits);
Spread operator should have better performance than array_merge
A significant advantage of Spread operator is that it supports any traversable objects, while the array_merge function only supports arrays.

To do this, you can loop through one and append to the other:
<?php
$test1 = array(
'11' => '11',
'22' => '22',
'33' => '33',
'44' => '44'
);
$test2 = array(
'44' => '44',
'55' => '55',
'66' => '66',
'77' => '77'
);
function combineWithKeys($array1, $array2)
{
foreach($array1 as $key=>$value) $array2[$key] = $value;
asort($array2);
return $array2;
}
print_r(combineWithKeys($test1, $test2));
?>
UPDATE: KingCrunch came up with the best solution: print_r($array1+$array2);

If you are using PHP 7.4 or above, you can use the spread operator ... as the following examples from the PHP Docs:
$arr1 = [1, 2, 3];
$arr2 = [...$arr1]; //[1, 2, 3]
$arr3 = [0, ...$arr1]; //[0, 1, 2, 3]
$arr4 = array(...$arr1, ...$arr2, 111); //[1, 2, 3, 1, 2, 3, 111]
$arr5 = [...$arr1, ...$arr1]; //[1, 2, 3, 1, 2, 3]
function getArr() {
return ['a', 'b'];
}
$arr6 = [...getArr(), 'c']; //['a', 'b', 'c']
$arr7 = [...new ArrayIterator(['a', 'b', 'c'])]; //['a', 'b', 'c']
function arrGen() {
for($i = 11; $i < 15; $i++) {
yield $i;
}
}
$arr8 = [...arrGen()]; //[11, 12, 13, 14]
It works like in JavaScript ES6.
See more on https://wiki.php.net/rfc/spread_operator_for_array.

This works:
$a = array(1 => 1, 2 => 2, 3 => 3);
$b = array(4 => 4, 5 => 5, 6 => 6);
$c = $a + $b;
print_r($c);

Warning! $array1 + $array2 overwrites keys, so my solution (for multidimensional arrays) is to use array_unique()
array_unique(array_merge($a, $b), SORT_REGULAR);
Notice:
5.2.10+ Changed the default value of sort_flags back to SORT_STRING.
5.2.9 Default is SORT_REGULAR.
5.2.8- Default is SORT_STRING
It perfectly works. Hope it helps same.

https://www.php.net/manual/en/function.array-merge.php
<?php
$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$result = array_merge($array1, $array2);
print_r($result);
?>

This is slightly explored by #jchook in one of his comments, but it is worth highlighting that the + is not as consistant as one might expect. When you are dealing with keys which are the same, the results are not the same as array_merge.
$a1 = array(
'hello',
'world',
);
$a2 = array(
'foo',
'baz',
);
// Will NOT work - only outputs $a1
print'<pre>';print_r($a1 + $a2);print'</pre>';
$a1 = array(
'a' => 'hello',
'b' => 'world',
);
$a2 = array(
'c' => 'foo',
'd' => 'baz',
);
// Will work (however were a and b c and d - would equally fail
print'<pre>';print_r($a1 + $a2);print'</pre>';
$a1 = array(
1=> 'hello',
2=> 'world',
);
$a2 = array(
3=>'foo',
4=>'baz',
);
// Will work
print'<pre>';print_r($a1 + $a2);print'</pre>';

We can combine two arrays in PHP using the spread operator (...).
In this example, $array1 contains the values 1 through 10, and $array2 contains the values 11 through 20.
The spread operator is used to concatenate(combine) the two arrays into a single array called $data.
// Define the first array
$array1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// Define the second array
$array2 = [11, 12, 13, 14, 15, 16, 17, 18, 19, 20];
// Use the spread operator to concatenate the two arrays into a single array
$data = [...$array1, ...$array2];
// Print the contents of the combined array
print_r($data);

Related

Merge column values from two arrays to form an indexed array of associative arrays

I have two arrays:
$a = ['0' => 1, '1' => 2, '2' => 3]
$b = ['0' => 4, '1' => 5, '2' => 6]
I want to create a new array like this:
[
['a' => 1, 'b' => '4'],
['a' => '2', 'b' => '5']
]
I have tried using array_merge and array_merge_recursive, but I wasn't able to get the right results.
$data = array_merge_recursive(array_values($urls), array_values($id));
You have to apply array_map() with custom function:
$newArray = array_map('combine',array_map(null, $a, $b));
function combine($n){
return array_combine(array('a','b'),$n);
}
print_r($newArray);
Output:-https://3v4l.org/okML7
Try this one
$c = array_merge($a,$b)
$d[] = array_reduce($d, 'array_merge', []);
It will merge the two array and reduce and remerge it.
You can use foreach to approach this
$a = ['0' => 1, '1' => 2, '2' => 3];
$b = ['0' => 4, '1' => 5, '2' => 6];
$res = [];
$i = 0;
$total = 2;
foreach($a as $k => $v){
$res[$i]['a'] = $v;
$res[$i]['b'] = $b[$k];
$i++;
if($i == $total) break;
}
The idea is to have an array $ab = ['a','b'] and a array from your both arrays like this $merged_array = [[1,4],[2,5],[3,6]]. Now we can combine array $ab with each element of $merged_array and that will be the result we need.
$first = ['0' => 1, '1' => 2, '2' => 3];
$second = ['0' => 4, '1' => 5, '2' => 6];
$merged_array = [];
for($i=0;$i<count($first);$i++)
{
array_push($merged_array,[$first[$i],$second[$i]]);
}
$final = [];
$ab = ['a','b'];
foreach($merged_array as $arr)
{
array_push($final,array_combine($ab, $arr));
}
print_r($final);
All earlier answers are working too hard. I see excessive iterations, iterated function calls, and counter variables.
Because there are only two arrays and the keys between the two arrays are identical, a simple foreach loop will suffice. Just push associative arrays into the result array.
Code: (Demo)
$a = ['0' => 1, '1' => 2, '2' => 3];
$b = ['0' => 4, '1' => 5, '2' => 6];
$result = [];
foreach ($a as $k => $v) {
$result[] = ['a' => $v, 'b' => $b[$k]];
}
var_export($result);
Output:
array (
0 =>
array (
'a' => 1,
'b' => 4,
),
1 =>
array (
'a' => 2,
'b' => 5,
),
2 =>
array (
'a' => 3,
'b' => 6,
),
)

Does PHP have built-in array function to remove specific key and return removed?

I want something that works like array_pop() or array_shift(), so it returns the removed element, but I'd like to specify by key which element to remove.
Example:
$arr = ['a' => 1, 'b' => 2, 'c' => 3];
$removed = array_remove($arr, 'b');
print_r($arr); // Outputs: Array(['a'] => 1, ['c'] => 3 )
print_r($removed); // Outputs: 2
Now I'am using
$arr = ['a' => 1, 'b' => 2, 'c' => 3];
$removed = $arr['b'];
unset($arr['b']);
array_splice() http://php.net/manual/en/function.array-splice.php
Omit replacement.

PHP: How to get both key and value from an associative array?

I have this associative array structure:
$multiArray = array(
'key1' => array(1, 2, 3, 4),
'key2' => array(5, 6, 7, 8),
'key3' => array(9, 10, 11, 12)
);
When I call $multiArray['key1'], I get the value (which is normal):
// Example 1
$multiArray['key1'];
//$multiArray only has [1, 2, 3, 4]
Is there a way that when I call I want $multiArray['key1'] that I can have ['key1' => array(1,2,3,4)] or the other two keys, depending on the situation?
I could structure $multiArray like so, but I was wondering if there is a better way.
// Example 2
$multiArray = array(
'keyA' => array('key1' => array(1, 2, 3, 4)),
'keyB' => array('key2' => array(5, 6, 7, 8)),
'keyC' => array('key3' => array(9, 10, 11, 12))
);
$multiArray['keyA'];
// $multiArray is now what I want: ['key1' => [1, 2, 3, 4]]
You could do something like this:
function getArray ($multiArray, $key) {
return array($key => $multiArray[$key]);
}
or
$result = array('key1' => $multiArray['key1']);
A little more context as to how you're using it would be useful though. It sounds like you already know the requested key at the point of use. If not you may need to use array_keys.
I think what you may be looking for is foreach:
$myArray = array('key1' => array(1, 2, 3), 'key2' => array(4, 5, 6));
$multiArray = array();
foreach ($myArray as $key => $value) {
// $key would be key1 or key2
// $value would be array(1, 2, 3) or array(4, 5, 6)
$multiArray[] = array($key => $value);
}

Combine two arrays

I have two arrays like this:
array(
'11' => '11',
'22' => '22',
'33' => '33',
'44' => '44'
);
array(
'44' => '44',
'55' => '55',
'66' => '66',
'77' => '77'
);
I want to combine these two array such that it does not contains duplicate and as well as keep their original keys. For example output should be:
array(
'11' => '11',
'22' => '22',
'33' => '33',
'44' => '44',
'55' => '55',
'66' => '66',
'77' => '77'
);
I have tried this but it is changing their original keys:
$output = array_unique( array_merge( $array1 , $array2 ) );
Any solution?
Just use:
$output = array_merge($array1, $array2);
That should solve it. Because you use string keys if one key occurs more than one time (like '44' in your example) one key will overwrite preceding ones with the same name. Because in your case they both have the same value anyway it doesn't matter and it will also remove duplicates.
Update: I just realised, that PHP treats the numeric string-keys as numbers (integers) and so will behave like this, what means, that it renumbers the keys too...
A workaround is to recreate the keys.
$output = array_combine($output, $output);
Update 2: I always forget, that there is also an operator (in bold, because this is really what you are looking for! :D)
$output = $array1 + $array2;
All of this can be seen in:
http://php.net/manual/en/function.array-merge.php
You should take to consideration that $array1 + $array2 != $array2 + $array1
$array1 = array(
'11' => 'x1',
'22' => 'x1'
);
$array2 = array(
'22' => 'x2',
'33' => 'x2'
);
with $array1 + $array2
$array1 + $array2 = array(
'11' => 'x1',
'22' => 'x1',
'33' => 'x2'
);
and with $array2 + $array1
$array2 + $array1 = array(
'11' => 'x1',
'22' => 'x2',
'33' => 'x2'
);
This works:
$output = $array1 + $array2;
The new way of doing it with php7.4 is Spread operator [...]
$parts = ['apple', 'pear'];
$fruits = ['banana', 'orange', ...$parts, 'watermelon'];
var_dump($fruits);
Spread operator should have better performance than array_merge
A significant advantage of Spread operator is that it supports any traversable objects, while the array_merge function only supports arrays.
To do this, you can loop through one and append to the other:
<?php
$test1 = array(
'11' => '11',
'22' => '22',
'33' => '33',
'44' => '44'
);
$test2 = array(
'44' => '44',
'55' => '55',
'66' => '66',
'77' => '77'
);
function combineWithKeys($array1, $array2)
{
foreach($array1 as $key=>$value) $array2[$key] = $value;
asort($array2);
return $array2;
}
print_r(combineWithKeys($test1, $test2));
?>
UPDATE: KingCrunch came up with the best solution: print_r($array1+$array2);
If you are using PHP 7.4 or above, you can use the spread operator ... as the following examples from the PHP Docs:
$arr1 = [1, 2, 3];
$arr2 = [...$arr1]; //[1, 2, 3]
$arr3 = [0, ...$arr1]; //[0, 1, 2, 3]
$arr4 = array(...$arr1, ...$arr2, 111); //[1, 2, 3, 1, 2, 3, 111]
$arr5 = [...$arr1, ...$arr1]; //[1, 2, 3, 1, 2, 3]
function getArr() {
return ['a', 'b'];
}
$arr6 = [...getArr(), 'c']; //['a', 'b', 'c']
$arr7 = [...new ArrayIterator(['a', 'b', 'c'])]; //['a', 'b', 'c']
function arrGen() {
for($i = 11; $i < 15; $i++) {
yield $i;
}
}
$arr8 = [...arrGen()]; //[11, 12, 13, 14]
It works like in JavaScript ES6.
See more on https://wiki.php.net/rfc/spread_operator_for_array.
This works:
$a = array(1 => 1, 2 => 2, 3 => 3);
$b = array(4 => 4, 5 => 5, 6 => 6);
$c = $a + $b;
print_r($c);
Warning! $array1 + $array2 overwrites keys, so my solution (for multidimensional arrays) is to use array_unique()
array_unique(array_merge($a, $b), SORT_REGULAR);
Notice:
5.2.10+ Changed the default value of sort_flags back to SORT_STRING.
5.2.9 Default is SORT_REGULAR.
5.2.8- Default is SORT_STRING
It perfectly works. Hope it helps same.
https://www.php.net/manual/en/function.array-merge.php
<?php
$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$result = array_merge($array1, $array2);
print_r($result);
?>
This is slightly explored by #jchook in one of his comments, but it is worth highlighting that the + is not as consistant as one might expect. When you are dealing with keys which are the same, the results are not the same as array_merge.
$a1 = array(
'hello',
'world',
);
$a2 = array(
'foo',
'baz',
);
// Will NOT work - only outputs $a1
print'<pre>';print_r($a1 + $a2);print'</pre>';
$a1 = array(
'a' => 'hello',
'b' => 'world',
);
$a2 = array(
'c' => 'foo',
'd' => 'baz',
);
// Will work (however were a and b c and d - would equally fail
print'<pre>';print_r($a1 + $a2);print'</pre>';
$a1 = array(
1=> 'hello',
2=> 'world',
);
$a2 = array(
3=>'foo',
4=>'baz',
);
// Will work
print'<pre>';print_r($a1 + $a2);print'</pre>';
We can combine two arrays in PHP using the spread operator (...).
In this example, $array1 contains the values 1 through 10, and $array2 contains the values 11 through 20.
The spread operator is used to concatenate(combine) the two arrays into a single array called $data.
// Define the first array
$array1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// Define the second array
$array2 = [11, 12, 13, 14, 15, 16, 17, 18, 19, 20];
// Use the spread operator to concatenate the two arrays into a single array
$data = [...$array1, ...$array2];
// Print the contents of the combined array
print_r($data);

where to use array() in PHP

can you give me examples of using array() function ?
There are plenty of examples in the manual:
http://php.net/manual/en/language.types.array.php
more specifically:
http://www.php.net/manual/en/function.array.php
$somearray = array();
$somearray[] = 'foo';
$somearray[] = 'bar';
$someotherarray = array(1 => 'foo', 2 => 'bar');
var_dump($somearray);
echo $someotherarray[2];
$a = array(1, 'test'=>2,'testing'=>'yes');
foreach($a as $key => $value) {
echo $key . ' = ' . $value . '<br />';
}
Even easier to see the output...
print_r($a);
$arr = array(1, 2, 3, 4, 5);
To loop over each element in the array:
foreach($arr as $val) {
print "$var\n";
}
One interesting thing to note about PHP arrays is that they are all implemented as associative arrays. You can specify the key if you want, but if you don't, an integer key is used, starting at 0.
$array = array(1, 2, 3, 4, 5);
is the same as (with keys specified):
$array = array(0 => 1, 1 => 2, 2 => 3, 3 => 4, 4 => 5);
is the same as:
$array = array('0' => 1, '1' => 2, '2' => 3, '3' => 4, '4' => 5);
Though, if you want to start the keys at one instead of zero, that's easy enough:
$array = array(1 => 1, 2 => 2, 3 => 3, 4 => 4, 5 => 5);
Though if you don't specify the key value, it takes the highest key and adds one, so this is a shortcut:
$array = array(1 => 1, 2, 3, 4, 5);
The key (left side) can only be an integer or string, but the value (right side) can be any type, including another array or an object.
Strings for keys:
$array = array('one' => 1, 'two' => 2, 'three' => 3, 'four' => 4, 'five' => 5);
Two easy ways to iterate through an array are:
$array = array('one' => 1, 'two' => 2, 'three' => 3, 'four' => 4, 'five' => 5);
foreach($array as $value) {
echo "$value\n";
}
foreach($array as $key => $value) {
echo "$key=$value\n";
}
To test to see if a key exists, use isset():
if (isset($array['one'])) {
echo "$array['one']\n";
}
To delete a value from the array, use unset():
unset($array['one']);

Categories