I am trying to compare two non-associative arrays to create a new array with the matches.
This is what I have though:
//This array has several entries
$a_firstarray = Array();
//This array has less entries than the first array
$a_secondarray = Array();
//This array should contain the matches of the first array and the second array in no particular order
$a_mergedarray
for($i=0;$i <=count($a_firstarray);$i++){
for($a=0;$a <=count ($a_secondarray);$a++){
if($a_firstarray[$i] == $a_secondarray[$a]){
$a_mergedarray[] = $a_activecategory[$i];
}
}
}
It doesn't work for some reason. I am also sure that PHP has some sort of function that does this. Any ideas? thanks in advance.
This is known as the "intersection" of two arrays. PHP provides array_intersect.
use array_intersect.
$result = array_intersect($array1, $array2);
Are you looking for array_intersect()?
http://php.net/manual/en/function.array-intersect.php
Related
I have an array in the array, and I want to make it just one array, and I can easily retrieve that data
i have some like
this
but the coding only combines the last value in the first array, not all values
is it possible to make it like that?
so that I can take arrays easily
I would make use of the unpacking operator ..., combined with array_merge:
$array['test2'] = array_merge(...array_merge(...$array['test2']));
In your case you need to flatten exactly twice, if you try to do it one time too much it will fail due to the items being actual arrays themselves (from PHP's perspective).
Demo: https://3v4l.org/npnTi
Use array_merge (doc) and ... (which break array to separate arrays):
function flatten($arr) {
return array_merge(...$arr);
}
$arr = [[["AAA", "BBB"]], [["CCC"]]];
$arr = flatten(flatten($arr)); // using twice as you have double depth
In your case, $arr is $obj["test2"]. If your object is json cast it to array first and if it is a string use json_decode
Live example: 3v4l
if you have a array then you can use the below code
if(!empty($array['test2'])){
$newarray = array();
foreach ($array['test2'] as $arrayRow) {
$newarray = array_merge($newarray,$arrayRow);
}
$array['test2'] = $newarray;
}
I want to compare all the sub arrays in the $ids and I want to return only the numbers that show up in all three arrays, so it would return 3 and 4 as an array.
$ids = [
[1,2,3,4],
[2,3,4],
[3,4,5],
];
expecting it to return
array(3,4)
UPDATE: My apologies, I left out the detail that I would not know how many arrays would be in the associative array, it could be 2 sub arrays, other times it could be 5. I appreciate all the answers I have received.
Obviously array_intersect is the solution How to get common values from two different arrays in PHP. If you know the number of sub-arrays and their indexes then it's as simple as:
$result = array_intersect($ids[0], $ids[1], $ids[2]);
However, if you need to do it for an unknown/variable number of sub-arrays and/or unknown indexes, use $ids as an array of arguments with call_user_func_array:
$result = call_user_func_array('array_intersect', $ids);
Or better use Argument unpacking via ... (PHP >= 5.6.0):
$result = array_intersect(...$ids);
Splice out the first subarray and then loop the rest and use array_intersect to filter the result to 3,4.
$res = array_splice($ids,0,1)[0];
foreach($ids as $id){
$res = array_intersect($res, $id);
}
var_dump($res); // 3,4
https://3v4l.org/Z7uZK
I have problem wiht array_merge():
First array:
$array1=array(
[0]=>array(["key1"]=>"value1",["key2"]=>"value2",["key3"]=>"value3")
);
Second array:
$array2=array(["key4"]=>"value4",["key5"]=>"value5",["key6"]=>"value6");
And I need merge this arrays to one like this:
$array1=array(
[0]=>array(["key1"]=>"value1",["key2"]=>"value2",
["key3"]=>"value3",["key4"]=>"value4",["key5"]=>"value5",["key6"]=>"value6"));
But when use:
$array3=array_merge($array1,$array2);
var_dump($array3);
var_dump return this:
array(
[0]=>array(["key1"]=>"value1",["key2"]=>"value2",
["key3"]=>"value3") ["key4"]=>"value4",["key5"]=>"value5",["key6"]=>"value6");
And don't know why.
Thanks
$array3=array(array_merge($array1[0],$array2));
you have to merge the inner array, not the outer one.
https://3v4l.org/dCm2F
Merging the first element from first array with the second one, may help:
$array3 = array();
$array3[0] = array_merge($array1[0], $array2);
I have an array that contains names of arrays
$names_array[] = ('$array1', '$array2', $array3'....)
The $names_array[] is dynamically updated so it may contain 2 or more different names.
When the script is executed the values of listed arrays in $names_array[] need to be merged.
I think in case of merging it is not a problem
u can merge $result = array_merge($array1, $array2);
http://php.net/manual/en/function.array-merge.php
I think it can be done with variable variables.
$arraymerge = array();
foreach ($names_array as $arrayname)
{
$arraymerge = array_merge($arraymerge, ${$arrayname});
}
Thanks for help... I have went around the problem: if anyone needs to merge dynamically generated arrays, in my case I have six arrays that exist or not, so I need to merge the existing ones. What I did is:
if(!is_array($array1[$i])) $array1[$i]=array();
if(!is_array($array2[$i])) $array2[$i]=array();
if(!is_array($array3[$i])) $array3[$i]=array();
if(!is_array($array4[$i])) $array4[$i]=array();
if(!is_array($array5[$i])) $array5[$i]=array();
if(!is_array($array6[$i])) $array5[$i]=array();
$combineddata[$i]=array_merge($array1[$i], $array2[$i],$array3[$i],$array4[$i], $array5[$i], $array6[$i]);
In case 'array_x[$i]' doesn't exists array_merge doesn't break the script just merges empty array.
Thanks
$names_array = array ('array1', 'array2', 'array3');
$array1 = array ('a','b','c');
$array2 = array ('d','e','f');
$array3 = array ('g','h','i');
$result = array ();
foreach ($names_array as $x) {
$result = array_merge ($result, $$x);
}
print_r ($result);
Is there a built-in function to get all members of array 1 which do not exist in array 2?
I know how to do it programatically, only wondering if there is a built-in function that does the same. So please, no code examples.
That sounds like a job for array_diff.
Returns an array containing all the
entries from array1 that are not
present in any of the other arrays.
array_diff is definitely the obvious choice but it is not technically the opposite of array interesect. Take this example:
$arr1 = array('rabbit','cat','dog');
$arr2 = array('cat','dog','bird');
print_r( array_diff($arr1, $arr2) );
What you want is a result with 'rabbit' and 'bird' in it but what you get is only rabbit because it is looking for what is in the first array but not the second (and not vice versa). to truly get the result you want you must do something like this:
$arr1 = array('rabbit','cat','dog');
$arr2 = array('cat','dog','bird');
$diff1 = array_diff($arr1, $arr2);
$diff2 = array_diff($arr2, $arr1);
print_r( array_merge($diff1, $diff2) );
Note: This method will only work on arrays with numeric keys.
$diff = array_diff($array1, $array2);
array_diff()
Just to clarify as I was looking into this question the answers of #Jon and #Dallas Caley are both correct depending on the domain of your arrays.
If the array against what you are comparing is the full domain of your results then a simple array_diff will suffice as per #Jon answer.
If the array against what you are comparing is NOT the full domain of your results then you should go with the double array_diff as per #Dallas Caley answer.