Merging and array by value instead of key in PHP - php

I have two arrays of values that I would like to combine - but the only methods that PHP provides seem to combine by key instead of value. Here is a hack that I was able to use to get this to work, but I am wondering if there is a better method or a native function that I have missed. It's been a while since I last used arrays and it seems like there is an easy answer to this.
//Input arrays that we want to combine into one array
$array = array(2, 3, 4, 5);
$array2 = array(5, 6, 1);
//Flip values and keys
$array = array_flip($array);
$array2 = array_flip($array2);
//Combine array
$array3 = $array2 + $array;
//flip array keys back to values
$array3 = array_keys($array3);
//Optional sort
sort($array3);
print_r($array3);
Which returns the combined values of the two arrays:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
)

Not entirely sure what you are trying to accomplish. I am assuming you are trying to combine 2 arrays without having any duplicates. If this is the case then the following would work
$newarr = array_unique(array_merge($array, $array2));

Related

How provide indexing to any array in php

i am trying to compare two arrays using php intersect function.
I am using following code
$input_array=array();
$input_array=explode("," , $_POST['list']);
$array = array();
$result1 =mysql_query("SELECT b_no FROM abc");
while($fetch_array=mysql_fetch_array($result1)){
$array[] = $fetch_array['b_no'];
}
$result=array_intersect($input_array,$array);
echo"<pre>";
print_r($result);
echo"</pre>";
and result is like this:
Array
(
[4] => 443829
[5] => 952040
)
The resultant array have not their own indexing. Is possible to provide indexing?
It is possible to provide indexing, but you will need to specify which indexing you want.
If the resulting indexing is not what you expected, please note that array_intersect() only compares the values of each array, and it retains the index or key from the first array of each match.
If your requirement is to also match on the keys of an associative array (although I am inferring you are not judging from your example) you can use array_intersect_assoc().
If you want to simply 'reset' the indexing you can use array_values(). For example:
<?php
$a = [2 => 1, 2, 3];
$b = [2, 3, 4];
$intersect = array_intersect($a, $b);
print_r($intersect);
// Original keys are retained:
//
// Array
// (
// [3] => 2
// [4] => 3
// )
print_r(array_values($intersect));
// Original keys are discarded:
//
// Array
// (
// [0] => 2
// [1] => 3
// )
On the other hand, if you had a specific set of keys you wanted to use, say for example ['foo', 'bar'] you can use array_combine() - it accepts two arrays, one as keys and the other as values, to explicitly define a new set of indexes or keys for an array. For example:
$keys = ['foo', 'bar'];
print_r(array_combine($keys, $intersect);
// Array
// (
// [foo] => 2
// [bar] => 3
// )
$indexes = [100, 200];
print_r(array_combine($indexes, $intersect));
// Array
// (
// [100] => 2
// [200] => 3
// )
Please note, array_combine() requires that the length of both arrays are the same. I cannot really provide any more detail unless you update your question but I hope this helps :)

Get array values which are not being compared

Currently, lets assume I have two arrays as follow:
$values1= array(1, 2, 3);
$values2= array(1, 3, 4);
If I compare both arrays in loop I would be able to differentiate which array elements of first array is not being compared. For example :
$data=array();
foreach($values1 as $value) {
if(! in_array($value, $values2 )) {
$data[]=$value;
}
}
In this way i would be figure out that 2 is the value which is not in the $value2 array but at the same time i also wanted to know what are the other extra elements which are not being compared in $valnues2 array such as 4 in this case.
Any help will be highly appreciated.
I hope you don't mind using a function, but you could merge them both and compare them to the ones with their similar values to get the differences. Like this:
$values1 = array(1, 2, 3);
$values2 = array(1, 3, 4);
$others = array_diff(array_merge($values1, $values2), array_intersect($values1, $values2));
echo '<pre>';
print_r($others);
Should output something like:
Array
(
[1] => 2
[5] => 4
)
array_diff() only checks for elements existing in arg 1 that don't exist in arg 2, one way to get around this is to check both ways and merge the results:
function array_diff_both($a, $b) {
$d1 = array_diff($a, $b);
$d2 = array_diff($b, $a);
return array_merge($d1, $d2);
}
print_r(array_diff_both($values1, $values2));
Example:
Array
(
[0] => 2
[1] => 4
)
Looking forward, it might be best to pass arrays in as an array so you could expand this function's use with the number of your arrays.

array_intersect a variable amount of arrays

I am creating a faceted search, and I'm am trying to use array_intersect to compare the arrays and find the inputs that match.
The problem is that I will have a variable amount of arrays at anytime depending on what filters the user has selected:
$array_1, $array_2, $array_3 etc...
How do I create an array_intersect function that is dynamic in this sense?
This is what I've tried:
$next_array = 0;
for($i = 0; $i < $array_count; $i++) {
$next_array++;
if ($i == 0) {
$full_array = ${array_.$i};
} else {
if(!empty(${cvp_array.$next_array})) {
$full_array = array_intersect($full_array, ${cvp_array_.$next_array});
}
}
}
------------- EDIT -------------
I'll try to narrow down my goal a bit more:
If the user clicks three filters, this results in three arrays being created with each having individual results:
Array_1 ( [0] => 2, [1] => 4, [2] => 6 )
Array_2 ( [0] => 1, [1] => 4, [2] => 6 )
Array_3 ( [0] => 6, [1] => 7, [2] => 8 )
I need code that will find the number that is in ALL of the arrays. And if there is no common number then it would end as false or something. In the case above, I'd need it to retrieve 6. If it was only the first two arrays, it would return 4 and 6.
Try this:
$fullArray = array($array1, $array2, $array3...);
call_user_func_array('array_intersect', $fullArray);
One can use:
$intersect = array_intersect(...$fullArray);
First of all, turn those arrays into an array of arrays. Then you can use array_reduce combined with array_intersect to reduce a variable amount of arrays down to one.
You can turn those array to a single array named $total_array by using array_combine(),
then use array_intersect($full_array, $total_array). I hope this useful

PHP 2 arrays - merge values existing in both arrays to one array

I have 2 arrays:
$array1 = array(1,2,3,4,5);
$array2 = array(3,4,5,6,7);
Is there any PHP function that does this?
$finalArray = unknown_php_function($array1,$array2);
// result: $finalArray = array(3,4,5);
It merges both arrays and removes values which aren't present in both arrays. Do I have to build a foreach cycle or is there an easier way? Thanks
You want array_intersect for this, basically the intersection of two sets (arrays, in this case), just like in school. :-)
You're looking for array_intersect(). Here is a demo:
$array1 = array(1,2,3,4,5);
$array2 = array(3,4,5,6,7);
$finalArray = array_intersect($array1,$array2);
print_r($finalArray);
Outputs:
Array
(
[2] => 3
[3] => 4
[4] => 5
)

How to define single and multidimensional array in PHP?

I am beginner in PHP programming. I want to know how to define single and multidimensional array in PHP.
There are a wide variety of ways to do this, all of which are well explained on the relevant PHP manual page.
However, in terms of some examples:
$singleArray = array(1, 2, 3);
$multiArray = array(array(1, 2, 3), array(4, 5, 6));
You of course can also use the following syntax:
$singleArray = $multiArray = array();
$singleArray[] = 1;
$singleArray[] = 2;
...
$multiArray[0][] = "Bob";
$multiArray[0][] = "Steve";
$multiArray[1][] = "Dave";
$multiArray[1][] = "Jack";
...
You can also provide you own keys (in addition to the numeric ones), such as:
$singleArray = array('first'=>1, 'second'=>2, 'third'=>3);
(Use array_keys to extract the keys from such an array.)
However, if you're just starting out, you really want to spend a bit of time reading the excellent online documentation, practising with the tutorials, etc. as this will be a lot faster that asking a multitude of questions on SO. :-)
Array elements in PHP can hold values of any type, such as numbers, strings and objects. They can also hold other arrays, which means you can create multidimensional, or nested, arrays.
Single dimensional Array :
$myArray = array(value1, value2, value3);
Multidimensional Array :
$myArray = array(
array( value1, value2, value3 ),
array( value4, value5, value6 ),
array( value7, value8, value9 )
);
Here, the top-level array contains 3 elements. Each element is itself an array containing 3 values.
Basically, there are three different types of arrays:
Numeric array – An array with a numeric ID key.
Multidimensional arrays – An array containing one or more arrays.
Associative arrays – An array where each ID key is associated with a value.
Read here for more about these types : Types of Arrays in PHP
Did you read the manual ?
Especially the exemples, like this one :
$fruits = array ( "fruits" => array ( "a" => "orange",
"b" => "banana",
"c" => "apple"
),
"numbers" => array ( 1,
2,
3,
4,
5,
6
),
"holes" => array ( "first",
5 => "second",
"third"
)
);

Categories