PHP array_merge() function - php

I have some problems during working with arrays using array_merge function. Here an example:
First example:
$first = array('01' => 1, '03' => 73);
$second = array('14'=>11, '15' => 23);
var_dump(array_merge($first, $second));
Result is:
array(4) { ["01"]=> int(1) ["03"]=> int(73) [0]=> int(11) [1]=> int(23) }
Expected:
array(4) { ["01"]=> int(1) ["03"]=> int(73) [14]=> int(11) [15]=> int(23) }
Second example:
$first = array('01'=>3, '03'=>10);
$second = array('05'=>44, '07'=>3);
var_dump(array_merge($first,$second));
Result is(as expected):
array(4) { ["01"]=> int(3) ["03"]=> int(10) ["05"]=> int(44) ["07"]=> int(3) }
Third example:
var_dump(array_merge(array("somekey"=> array("some value"))));
Result is(as expected):
array(1) { ["somekey"]=> array(1) { [0]=> string(10) "some value" } }
Fourth example:
var_dump(array_merge(array("34"=> array("some value"))));
Result is:
array(1) { [0]=> array(1) { [0]=> string(10) "some value" } }
Expected:
array(1) { [0]=> array(1) { ["34"]=> string(10) "some value" } }
var_dump(array_merge(array("34"=> array("some value"))));
As you can see from third and fourth examples I set string for keys but the result was not as expected.
What is wrong or incorrect of understanding?
Thanks for helping.
Edited. Why (example first and second) the result is different, but the keys are string and consist of only with digest?

Quoting from the manual:
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.
Values in the input array with numeric keys will be renumbered with
incrementing keys starting from zero in the result array.
Keys with a leading zero are being treated as strings, while numeric keys without a leading zero are being treated as numeric
If you want to retain the keys exactly as they are:
$first = array('01' => 1, '03' => 73);
$second = array('14'=>11, '15' => 23);
var_dump(
array_combine(
array_merge(
array_keys($first), array_keys($second)
),
array_merge(
$first, $second
)
)
);
as long as keys are unique between $first and $second

Definition : 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.
Values in the input array with numeric keys will be renumbered with incrementing keys starting from zero in the result array.
INPUT
<?php
$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$result = array_merge($array1, $array2);
print_r($result);
?>
OUTPUT
Array
(
[color] => green
[0] => 2
[1] => 4
[2] => a
[3] => b
[shape] => trapezoid
[4] => 4
)
Hope it helps:)

Try array_merge() like below:-
$first = array('01' => 1, '03' => 73);
$second = array('14'=>11, '15' => 23);
$output = array_merge($first, $second);
print_r($output);
EDIT:-
$first = array('01' => 1, '03' => 73);
$second = array('14'=>11, '15' => 23);
$output = $first + $second;
print_r($output);

Related

Array comparision in php to get only difference

Following Below are two arrays which i wanna compare and remove the same values something like array_diff() Function and i want to store the result in third array
$array1 = Array([0] => Array([a] => XYZ,[b] => ABC))
$array2 = Array([0] => Array([a] => XYZ,[b] => ABC),[1] => Array([a] => PQR,[b] => XYZ))
$array3 = array_diff($array1,$array2);
//$array3 value must return this value Array([1] => Array[a]=> PQR,[b] => XYZ)
I don't know what i am doing wrong but i am getting error that array cannot be converted into string. Can anyone help me with this?
Thanks in advance
If you are sure that your $array2 will always contain more elements than $array1 then here is your solution:
$array1 = array(array('a' => 'XYZ','b' => 'ABC'));
$array2 = array(array('a' => 'XYZ','b' => 'ABC'),array('a' => 'PQR','b' => 'XYZ'));
$limit = count($array2);
$array3 = array();
for($i=0;$i<$limit;$i++){
if(empty($array1[$i]))
$array3[] = $array2[$i];
$array3[] = array_diff($array1[$i],$array2[$i]);
}
foreach($array3 as $k=>$a3){
if(empty($a3)||($a3===NULL))
continue;
$result[$k] = $a3;
}
var_dump($result); //array(1) { [1]=> array(2) { ["a"]=> string(3) "PQR" ["b"]=> string(3) "XYZ" } }
Please note that array_diff works on 1D array and you was providing 2D arrays as parameter and that's why it wasn't working.
Also your way of defining $array1 and $array2 is wrong, please check this solution for right syntax.
I hope it helps

Php array_intersect output [duplicate]

This question already has answers here:
How to reindex an array?
(6 answers)
Closed last year.
i'm having trouble with how array works.
$a = array("24","33","12");
$b = array("24","12");
$c = array_intersect($a,$b);
echo json_encode($c);
// {"0":"24","2":"12"}
I expect the output to be like this:
// ["24","12"]
How can i achieve that output?
echo json_encode(array_values($c));
output
["24","12"]
array_intersect Computes the intersection of arrays
<?php
$array1 = array(2, 4, 6, 8, 10, 12);
$array2 = array(1, 2, 3, 4, 5, 6);
var_dump(array_intersect($array1, $array2));
var_dump(array_intersect($array2, $array1));
?>
will yield
array(3) {
[0]=> int(2)
[1]=> int(4)
[2]=> int(6)
}
array(3) {
[1]=> int(2)
[3]=> int(4)
[5]=> int(6)
}
. json_encode returns string containing the JSON representation of value. For example
<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
?>
will output
{"a":1,"b":2,"c":3,"d":4,"e":5}
As mamta answered you can use array_values to return all the values of an array and json_encode it like
echo json_encode(array_values($c))

Get a value from a key of two arrays

ARRAY 1:
array(1) {
["en"]=>
array(1) {
["em"]=> null
}
}
ARRAY 2 VALUES:
array(15) {
["something"]=>
array(4) {
["somekey1"]=>
string(25) "value1"
["somekey2"]=>
string(9) "value2"
["somekey3"]=>
string(5) "value3"
["somekey4"]=>
string(3) "value4"
}
["en"]=>
array(3) {
["em"]=>
string(4) "RESULT"
Look at array on ["en"]["em"] = "RESULT" from both arrays.
I want using $array1 and $array2 to intersecting a keys of array and get a result from $array2:
NOTE: On Array1 can be more nested arrays, ARRAY1 should find this keys on ARRAY2:
NOTE: I don't want to grab a data like $array2["en"]["em"], only using custom functions. (for example: custom array_intersect())
I have 2 arrays. Look at only keys. On Array1 there is en,em keys. I want these two keys to intersecting on Array2. When is intersecting with Array2, it will on Array2 get a value en,em->RESULT. I don't want a classical way to grab a data, just a COMPARE TWO ARRAYS and GET A VALUE.
I've tried intersecting, but this ONLY works if two arrays ARE SAME. So, I need to intersecting using nested recursive searching by key!
Example, I don't want:
$array2['en']['em'];
some_function_to_search_array_by_key(array $array2);
Example, that I WANT to:
Using function `array_intersect()` or some hardcoded sample.
get_result_by_two_arrays($array1, $array2);
Example of Result:
INPUT:
// search by arrays keys
$array1 = array('en' => 'em');
$result = get_result_by_two_arrays($array1, $array2);
RESULT:
$result =
(string)RESULT;
Here is a simple example of what I think you want :
$array1 = ['en' => ['em' => null]];
$array2 = ['en' => ['em' => 'RESULT'], 'something' => ['somekey1' => 'somevalue1', 'somekey2' => 'somevalue2']];
function get_result_by_two_arrays(array $array1, array $array2) {
if (!$array1) return;
do {
$key = current(array_keys($array1));
$array1 = current($array1);
if (!isset($array2[$key])) return;
$array2 = $array2[$key];
} while (is_array($array1));
return $array2;
}
var_dump( get_result_by_two_arrays($array1, $array2) );
# string(6) "RESULT"

Move key-specified element to the front of an associative array

I have an array with string indices, that I need partially sorted. That is, some elements must be moved first, but the others should remain untouched in their current (PHP-internal) order:
# The element with key "c" should be first
$foo = array(
"a" => 1,
"b" => 2,
"c" => 3,
"d" => 4,
);
uksort($foo, function ($a, $b) {
if ($a === "c") {
return -1;
} elseif ($b === "c") {
return 1;
}
return 0;
});
var_dump($foo);
What I expected:
array(4) { ["c"]=> int(3) ["a"]=> int(1) ["b"]=> int(2) ["d"]=> int(4) }
//--------------------------^ "a" remains first of the unsorted ones
What I got:
array(4) { ["c"]=> int(3) ["d"]=> int(4) ["b"]=> int(2) ["a"]=> int(1) }
//--------------------------^ "d" moved above "a"
This seems due to the sorting algorithm uksort() uses internally, which destroys the fragile order of elements. Is there any other way to achieve this sorting?
Using any sort function is overkill for this task. You merely need to merge the input array into a lone array containing the element which should come first. The array union operator (+) will do nicely for your associative array (otherwise array_merge() will do).
Codes: (Demos)
if key c is guaranteed to exist:
$foo = array(
"a" => 1,
"b" => 2,
"c" => 3,
"d" => 4,
);
$foo = ['c' => $foo['c']] + $foo;
var_export($foo);
if key c might not exist check for it first:
$bar = array(
"a" => 1,
"b" => 2,
"d" => 4,
);
if (array_key_exists('c', $bar)) {
$bar = ['c' => $bar['c']] + $bar;
}
var_export($bar);
Output:
array (
'c' => 3,
'a' => 1,
'b' => 2,
'd' => 4,
)
and
array (
'a' => 1,
'b' => 2,
'd' => 4,
)
This worked for me and returned:
array(4) { ["c"]=> int(3) ["a"]=> int(1) ["b"]=> int(2) ["d"]=> int(4) }
<?php
# The element with key "c" should be first
$foo = array(
"a" => 1,
"b" => 2,
"c" => 3,
"d" => 4,
);
uksort($foo, function ($a, $b) {
if ($a === "c") {
return -1;
} else
return 1;
});
var_dump($foo);
?>

Re-sorting array via array keys?

I have two arrays, $country and $redirect with each entry corresponding with it's exact counterpart e.g. $redirect[1] and $country[1].
After un-setting values throughout the array, I might be left with, for example, an array where only $var[4] and $var[2] are set. I want to re-assign array keys from 0 upwards, so that $var[2] would have it's key re-assigned to $var[0] and $var[4] re-assigned to $var[1].
Essentially the sort() function, but sorting by current array key, as oppose to the numeric/string value of an array.
Is this possible?
Any answers or advice would be greatly appreciated ;)!
UPDATE:
I've attempted to use both ksort() and array_values(), however I'm not sure they're really what I need, as I plan on using the size_of() function.
My code:
$var = array(2 => "value_1", 4 => "value_2", 6 => "value_3");
ksort($var);
for($i = 0, $size = sizeof($var); $i < $size; $i++) {
$var[$i] = "foo";
}
var_dump($var);
Returns:
array(5) { [2]=> string(3) "foo" [4]=> string(7) "value_2" [6]=> string(7) "value_3" [0]=> string(3) "foo" [1]=> string(3) "foo" }
Any additional ideas/answers on how I could get this to work would be greatly appreciated!
Use array_values() (returns "sorted" array):
$var = array(2 => "value_1", 4 => "value_2", 6 => "value_3");
$var = array_values($var);
for($i = 0, $size = sizeof($var); $i < $size; $i++) {
$var[$i] = "foo";
}
var_dump($var);

Categories