pretty straightforward question actually..
is it possible in PHP to combine two separate arrays of the same length to one associative array where the values of the first array are used as keys in the associative array?
I could ofcourse do this, but I'm looking for another (built-in) function, or more efficient solution..?
function Combine($array1, $array2) {
if(count($array1) == count($array2)) {
$assArray = array();
for($i=0;$i<count($array1);$i++) {
$assArray[$array1[$i]] = $array2[$i];
}
return $assArray;
}
}
array_combine($keys, $values)
PS: Click on my answer! Its also a link!
you need array_combine.
<?php
$a = array('green', 'red', 'yellow');
$b = array('avocado', 'apple', 'banana');
$c = array_combine($a, $b);
print_r($c);
?>
There’s already an array_combine function:
$combined = array_combine($keys, $values);
hello everybody i will show you how to merge 2 arrays in one array
we have 2 arrays and i will make one array from them
$data_key = array('key1','key2');
$data_value = array('val1','val2');
lets declare the main array
$main_array = array();
now let's fill it with the 2 arrays
foreach ($data_key as $i => $key) {
$main_array[$key] = $data_value[$i];
}
now let's see the result by using var_dump($main_array);
array(2) {
["key1"]=> string(4) "val1"
["key2"]=> string(4) "val2"
}
i hope that can help someone :)
Related
This question already has answers here:
How to filter an associative array comparing keys with values in an indexed array?
(12 answers)
Closed 3 years ago.
I have 2 arrays one is the collection of key and other with a collection of data ex.
$array1 = ['0'=>'A1','1'=>'A2','2'=>'A3'];
and
$array2 = ['A1'=>'Data1','A2'=>'Data2','A3'=>'Data3','A4'=>'Data4','A5'=>'Data5'];
I want data like this
$array = ['A1'=>'Data1','A2'=>'Data2','A3'=>'Data3']
you can use array_filter for this:
$my_array = ['A1'=>'Data1','A2'=>'Data2','A3'=>'Data3','A4'=>'Data4','A5'=>'Data5'];
$allowed = ['0'=>'A1','1'=>'A2','2'=>'A3'];
$filtered = array_filter(
$my_array,
function ($key) use ($allowed) {
return in_array($key, $allowed);
},
ARRAY_FILTER_USE_KEY
);
var_dump($filtered);
Output:
array(3) {
["A1"]=>
string(5) "Data1"
["A2"]=>
string(5) "Data2"
["A3"]=>
string(5) "Data3"
}
Demo: https://3v4l.org/ZvkJb
Credit: PHP: How to use array_filter() to filter array keys?
You can also try this one to get the exact data of $array2 as you mentioned in the question.
$array1 = ['0'=>'A1','1'=>'A2','2'=>'A3'];
$array2 = ['A1'=>'Data1','A2'=>'Data2','A3'=>'Data3','A4'=>'Data4','A5'=>'Data5'];
$ans = [];
foreach($array1 as $value)
{
if(isset($array2[$value]))
$ans[$value] = $array2[$value];
}
print_r($ans);
You can make $array1 a dic, then check if key in $array2 is set in the dic.
$array1 = array_flip($array1);
$result = [];
foreach($array2 as $k => $v){
if(isset($array1[$k])){
$result[$k] = $v;
}
}
This question already has answers here:
Two arrays in foreach loop
(24 answers)
Closed 5 months ago.
I want to loop for more than one array i was able to do for two using this code
$value=array_combine($val1,$val2);
foreach($value as $vl1=> $vl2)
Am now trying to do for more than two using this code but its not working
I don't know where am getting it wrong.
$value=array_combine($val1,$val2,$val3,$val4,$val5,val6);
foreach($value as $vl1=> $vl2,$vl3=> $vl4,$vl5=> $vl6 )
Thanks
Edited
Here's is the complete working code - Thanks to #Barmar
With this code, i was able to submit multiple columns and rows into the database.
if(isset($_POST['submit'])){
$head = $_POST['head'];
$surname = $_POST['surname'];
$othernames = $_POST['othernames'];
$affiliate_email = $_POST['affiliate_email'];
$affiliation = $_POST['affiliation'];
$phone_no = $_POST['phone_no'];
$value=array_combine($surname,$affiliate_email,$othernames,
$head,$affiliation,$phone_no);
foreach ($surname as $index => $sur) {
$affmail = $affiliate_email[$index];
$names = $othernames[$index];
$hd = $head[$index];
$affil = $affiliation[$index];
$phone = $phone_no[$index];
$page3="INSERT INTO tbl_name
(affiliate_email,surname,othernames,affiliation,phone_no,head) VALUES
'$affmail','$sur','$names','$affil','$phone','$hd')";
if(mysqli_query($db->connection, $page3)) {
header("location:page4?code=$app_code");
}
}
}
array_combine() can only take two arrays -- it creates an associative array that uses the first array as the keys, and the second array as the corresponding values. It makes no sense to give it more than 2 arrays, where would those elements go in this result?
Loop over one array, and use its index to access the other arrays.
foreach ($array1 as $index => $val1) {
$val2 = $array2[$index];
$val3 = $array3[$index];
...
}
What you are looking for is array_merge or array_merge_recursive depending on your actual array structure.
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.
Example
$arr1 = [1, 2, 3, 4, 5];
$arr2 = [6, 7, 8, 9, 10];
$arr3 = ['name' => 'Script47'];
$res = array_merge($arr1, $arr2, $arr3);
var_dump($res);
Output
array(11) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
[3]=>
int(4)
[4]=>
int(5)
[5]=>
int(6)
[6]=>
int(7)
[7]=>
int(8)
[8]=>
int(9)
[9]=>
int(10)
["name"]=>
string(8) "Script47"
}
Thereafter, you can loop through the resultant array as a single using foreach($array as $key => $value) { }.
Live Example
Repl
Technically you can't loop over more then one "Thing" at a time.
But, if the arrays are correlated, (related). So say array1 => item1 is related to array2 => item1 is related to array3 => item1. Then I would suggest structuring your arrays like this:
Take this example
$array1 = [a1-item1,a1-item2,a1-item3];
$array2 = [a2-item1,a2-item2,a2-item3];
$array3 = [a3-item1,a3-item2,a3-item3];
And structure it like this (basically a matrix)
$combined1 = [
[a1-item1,a1-item2,a1-item3],
[a2-item1,a2-item2,a2-item3],
[a3-item1,a3-item2,a3-item3]
];
Then array_column(0) gives you all item1's, and $combined[0] gives you all of array1.
Conversely you can do it the opposite way too.
$combined2 = [
[a1-item1,a2-item1,a3-item1],
[a1-item2,a2-item2,a3-item2],
[a1-item3,a2-item3,a3-item3]
];
And then array_column(0) gives you array1, and $combined[0] gives you all of item 1's.
Which ever way makes more sense for what you are doing. The only difference is what you get in the foreach loop.
foreach($combined1 as $array){
print_r($array);
}
//Outputs: [a1-item1,a1-item2,a1-item3]
foreach($combined2 as $array){
print_r($array);
}
//Outputs: [a1-item1,a2-item1,a3-item1]
And then you can loop over it to your heart's content whichever way you want.
Then you could flip this middle one like
$combined1 = [
[a1-item1,a1-item2,a1-item3],
[a2-item3,a2-item2,a2-item1],
[a3-item1,a3-item2,a3-item3]
];
Just kidding, don't do that it will mess you all up... lol
Make sense.
Why it's not working
array_combine only accepts two arguments:
http://php.net/manual/en/function.array-combine.php
You can neither use foreach like that. You may only have one key and one value for each foreach, but you can use a foreach inside another foreach.
Something like array_combine with undefinable arguments number
Assuming that you really want to use that functionality, but with several arrays at the same time, you could implement something like this if you're using PHP 7 or a greater version:
<?php
function array_combine_many(array ...$keysAndValues)
{
$length = count($keysAndValues);
if ($length % 2 != 0) {
throw new \Error("The number of arguments should be even. It's: $length.");
}
$combinations = array();
for ($i = 0; $i < $length; ++$i) {
$combinations[] = array_combine(
$keysAndValues[$i],
$keysAndValues[++$i]
);
}
return $combinations;
}
If you're not using PHP 7 or a greater version, you have to use the func_get_args function:
<?php
function array_combine_many()
{
$keysAndValues = func_get_args();
$length = count($keysAndValues);
// etc...
foreach inside a foreach
You may use the implemented function like this:
<?php
$val1 = ['a', 'b', 'c'];
$val2 = ['12', '34', '56'];
$val3 = ['d', 'e', 'f', 'g'];
$val4 = ['156', '67', '5678', '346'];
$val5 = ['h'];
$val6 = ['3487'];
$combinations = array_combine_many($val1, $val2, $val3, $val4, $val5, $val6);
foreach ($combinations as $combination) {
foreach ($combination as $key => $val) {
echo "$key => $val\n";
}
}
Output:
a => 12
b => 34
c => 56
d => 156
e => 67
f => 5678
g => 346
h => 3487
Using array_map, array_merge and call_user_func_array
Here's another solution:
<?php
$merged = call_user_func_array(
'array_merge',
array_map(
function (array $args) {
return array_combine($args[0], $args[1]);
},
[
[$val1, $val2],
[$val3, $val4],
[$val5, $val6]
]
)
);
foreach ($merged as $key => $value) {
echo "$key => $value\n";
}
Someone could be so nice to tell me how to do the following with 2 ore more arrays in PHP:
array 1 (a,b,c,d)
array 2 (1,2,3,4)
I would like to merge the two arrays in an unique array with the merged values:
Result: unique array (a-1,b-2,c-3,d-4).
Is there any function that does so? I could not find anything in the forum either on the web.
Thanks for all your answers but I guess that my arrays are a bit more structured because I need the final result for a dropdown field.
Now I have these 2 arrays:
$array1[] = array( 'text' => $hospital['value'], 'value' => $hospital['value'] );
$array2[] = array( 'text' => $company['value'], 'value' => $company['value'] );
I want to have a final array that contains: Hospital1 - Company1, Hospital2 - Company2, Hospital3 - Company3, etc..
Thanks
You can use array_map:
$result = array_map(function ($item1, $item2) {
return "$item1-$item2";
}, $array1, $array2);
Here is working demo.
You would have to create a loop to do this manually. it might look something like the following:
$a = array(a,b,c,d);
$b = array(1,2,3,4);
$c = array(); //result set
if(count($a) == count($b)){ // make sure they are the same length
for($i = 0; $i < count($a); $i++){
$c[] = $a[$i]."-".$b[$i];
}
}
print_r($c);
If i understand right, you can use array_combine where array 1 will be the key and array 2 the value.
Example usage:
$a = array(1,2,3,4);
$b = array(a,b,c,d);
$c = array_combine($a, $b);
var_dump($c);
What I have
$array1 = [1,1,1];
$array2 = [1,1];
What I'm doing:
array_diff( $array1, $array2 );
What I expected:
array(1) { 1 }
What I got
array(0) { }
How do I subtract two arrays to get every discrepancy?
Edit:
My example was incomplete, sorry.
If we also have values like this:
$array1 = [1,1,2,1];
$array2 = [1,1,1,2];
I would expect
[1,1,2,1] - [1,1,1,2] = []
array_diff_assoc() is the right way to go here. But to get your expected result you just have to sort the array first with usort() where I compare the values with strcasecmp().
So this should work for you:
<?php
$array1 = [1,1,2,1];
$array2 = [1,1,1,2];
function caseCmpSort($a, $b){
return strcasecmp($a, $b);
}
usort($array1, "caseCmpSort");
usort($array2, "caseCmpSort");
$result = array_diff_assoc($array1, $array2);
print_r($result);
?>
output:
Array ( )
use array_diff_assoc
$array1 = [1,1,1];
$array2 = [1,1];
print_r(array_diff_assoc( $array1, $array2)); // outputs Array ([2] => 1)
try it here http://sandbox.onlinephpfunctions.com/code/43394cc048f8c9660219e4fa30386b53ce4adedb
So you should check array key differences too. Have you tried array_diff_assoc()?
http://php.net/manual/en/function.array-diff-assoc.php
From manual:
Returns an array containing all the entries from array1 that are not present in any of the other arrays.
So, it is working as expected. I am not sure what exactly You want to achieve. You cloud try, it should give You expected result in this example.
$a = [1,1,1];
$b = [1,1];
print_r(array_diff_assoc($a,$b));
Edit: Well, simple sort should solve issue from Your comment. Nothe, that this will remove information of original indexes of elements.
$a = [1,1,2,1];
$b = [1,1,1,2,1];
sort($a);
sort($b);
print_r(array_diff_assoc($a,$b));
<?php
$n = array(1,1,1);
$m = array(1,1);
$r = array_diff_assoc($n,$m);
var_dump($r);
?>
$arr1 = array('potato'=>1,'tomato'=>2,'apple'=>5,'banana'=>10);
$arr2 = array('orange'=>20,'tomato'=>3,'apple'=>5,'banana'=>20);
I need function that would return array('tomato','banana'), consider that it omits keys that don't exist in one or the other array. Apple has the same value in both arrays, so it should be omitted - returned should be only keys whose values differ and are set
This should work (demo):
$arr1 = array('potato'=>1,'tomato'=>2,'apple'=>5,'banana'=>10);
$arr2 = array('orange'=>20,'tomato'=>3,'apple'=>5,'banana'=>20);
$result = array_keys(array_diff(array_intersect_key($arr1, $arr2), $arr2));
print_r($result);
Output:
Array
(
[0] => tomato
[1] => banana
)
Reference:
array_intersect_key — Computes the intersection of arrays using keys for comparison
array_diff — Computes the difference of arrays
array_keys — Return all the keys or a subset of the keys of an array
$array3 = array();
foreach(array_intersect_key($array1, $array2) as $key => $v){
if($array1[$key] != $array2[$key]) $array3[] = $key;
}
<?php
/**
* Returns an array which contains keys which are in both $array1
* and $array2, and which have different values.
*/
function getKeysWhichMatchAndHaveDifferentValues($array1, $array2)
{
$arrIntersected = array_intersect_key($array1, $array2);
foreach($arrIntersected as $key => $value)
{
if($array2[$key] == $value) {
unset($arrIntersected[$key]);
}
}
return array_keys($arrIntersected);
}
$arr1 = array('potato'=>1,'tomato'=>2,'apple'=>5,'banana'=>10);
$arr2 = array('orange'=>20,'tomato'=>3,'apple'=>5,'banana'=>20);
$final = getKeysWhichMatchAndHaveDifferentValues($arr1, $arr2);
echo '<pre>' . print_r($final) . '</pre>';
?>
I would do simple loop.
Of course if you will need to compare large arrays, the native PHP functions could help a lot. Still can't answer right now what would be the most optimal way to do this.
You could do this using array_intersect and array_keys.
$arr3 = array_intersect(array_keys($arr1), array_keys($arr2));