Let's say I Have two arrays.
$arr1 = ['A','B','C','D'];
$arr2 = ['C','D'];
now compare two arrays.if there is no match for value of $arr1 in $arr2 then index is left empty.
for the above arrays output should be:
$arr3 = ['','','C','D']
I tried array_search() function.But couldn't achieve desired output.
Any possible solutions?
You can use foreach with in_array and array_push like:
$arr1 = ['A','B','C','D'];
$arr2 = ['C','D'];
$arr3 = [];
foreach($arr1 as $value){
$arr3[] = (in_array($value, $arr2)) ? $value : '';
}
print_r($arr3);
/*
Result
Array
(
[0] =>
[1] =>
[2] => C
[3] => D
) */
Foreach the first array then test with in_array if exist, if true push into array 3 else push empty value
You can use the following function. In the following code, the function search_in_array return true and false based on the searching within the 2nd array. So you can push the empty or searched value in final array.
<?php
$arr1 = array('A','B','C','D');
$arr2 = array('C','D');
$arr3 = array();
function search_in_array ($value, $array)
{
for ($i=0; $i<count($array); $i++)
{
if ($value == $array[$i])
{
return true;
}
}
return false;
}
for ($i=0; $i<count($arr1); $i++)
{
$value = $arr1[$i];
$result = search_in_array ($value, $arr2);
if ($result)
{
array_push ($arr3, $value);
}
else
{
array_push ($arr3, '');
}
}
print_array($arr3);
?>
Related
I have 2 arrays as follows:
$arr = array('one.jpg', 'two.jpg', 'three.jpg');
$arr1 = array('', 'five.jpg', '');
Now I want to make these two arrays to one array with following value:
$newArray = array('one.jpg', 'five.jpg', 'three.jpg');
How can I do this using PHP?
Use array_filter to remove the empty values.
Use array_replace to replace the values from the first array with the remaining values of the 2nd array.
$arr1=array_filter($arr1);
var_dump(array_replace($arr,$arr1));
Assuming you want to overwrite entries in the first array only with truthy values from the second:
$newArray = array_map(function ($a, $b) { return $b ?: $a; }, $arr, $arr1);
You can iterate through array and check value for second array :
$arr = array('one.jpg', 'two.jpg', 'three.jpg');
$arr1 = array('', 'five.jpg', '');
$newArray =array();
foreach ($arr as $key => $value) {
if(isset($arr1[$key]) && $arr1[$key] != "")
$newArray[$key] = $arr1[$key];
else
$newArray[$key] = $value;
}
var_dump($newArray);
Simple solution using a for loop, not sure whether there is a more elegant one:
$arr = array('one.jpg', 'two.jpg', 'three.jpg');
$arr1 = array('', 'five.jpg', '');
$newArray = array();
$size = count($arr);
for($i = 0; $i < $size; ++$i) {
if(!empty($arr1[$i])){
$newArray[$i] = $arr1[$i];
} else {
$newArray[$i] = $arr[$i];
}
}
I have an array like the one below:
$v = array(1,2,3,4,2,3);
How do I get the keys of all elements in array where the value is equal to 2?
If you have a value in an array and you want to get the keys you can use array_keys() with the optional search_value:
$v = array(1,2,3,4,2,3);
$keys = array_keys($v, '2');
print_r($keys);
// Array
// (
// [0] => 1
// [1] => 4
// )
For the output check https://3v4l.org/N8EBH
You can do it like
<?php
$v = array(1,2,3,4,2,3);
$keys = array();
foreach($v as $k=>$x)
{
if($x == 2)
$keys[] = $k;
}
echo "<pre>";print_r($keys);echo "</pre>";
Try this code
$v = array(1,2,3,4,2,3);
$a = 2;
$key = array();
foreach($v as $k=>$val)
{
if($a == $val)
{
$key[] = $k;
}
}
print_r($key);
If i have two array as following:
$array1 = array(array('id'=>11,'name'=>'Name1'),array('id'=>22,'name'=>'Name2'), array('id'=>33,'name'=>'Name3'),array('id'=>44,'name'=>'Name4'),array('id'=>55,'name'=>'Name5'));
$array2 = array(array('id'=>22,'name'=>'Name2'),array('id'=>55,'name'=>'Name5'));
My expect result, the array2 should be always at the beginning :
$newarray = array(array('id'=>22,'name'=>'Name2'),array('id'=>55,'name'=>'Name5'), array('id'=>11,'name'=>'Name1'), array('id'=>33,'name'=>'Name3'),array('id'=>44,'name'=>'Name4'));
My current solution is using two for loops:
foreach($array2 as $Key2 => $Value2) {
foreach($array1 as $Key1 => $Value1){
if($Value1['id'] != $Value2['id']) {
//push array
}
}
}
Edit:
The result "$newarray" should not include the duplicate ids from array1.
But i am looking for a faster and simpler solution.
SOLUTION:
$a1 = array();
foreach ($array1 as $v) $a1[$v['uuid']] = $v;
$a2 = array();
foreach ($array2 as $v) $a2[$v['uuid']] = $v;
$filtered = array_values(array_diff_key($a1, $a2));
//print_r($filtered);
$newarray = array_merge($array2, $filtered);
Thank you guys!!!!
Thanks.
Regards Jack
you want $new_array = array_merge($array2, $array1); puts the second array onto the end of the first one
You can use array_merge() function for that, like this:
$newarray = array_merge($array2, $array1);
I am not sure about your requirement but to sort multi-dimensional array on some specific key
You need to use usort function
Try the code below:
$cmp = function ($a, $b){
$a_val = $a['id'];
$b_val = $b['id'];
if ( $a_val == $b_val) {
return 0;
}
return ($a_val < $b_val) ? -1 : 1;
};
usort($array2,$cmp);
$array2 will be sorted by 'id'
array one: 1,3,5,7
array two: 2,4,6,8
the array i want would be 1,2,3,4,5,6,7,8
I'm just using numbers as examples. If it was just numbers i could merge and sort but they will be words. So maybe something like
array one: bob,a,awesome
array two: is,really,dude
should read: bob is a really awesome dude
Not really sure how to do this. Does PHP have something like this built in?
You could write yourself a function like this:
function array_merge_alternating($array1, $array2) {
if(count($array1) != count($array2)) {
return false; // Arrays must be the same length
}
$mergedArray = array();
while(count($array1) > 0) {
$mergedArray[] = array_shift($array1);
$mergedArray[] = array_shift($array2);
}
return $mergedArray;
}
This function expects two arrays with equal length and merges their values.
If you don't need your values in alternating order you can use array_merge. array_merge will append the second array to the first and will not do what you ask.
Try this elegant solution
function array_alternate($array1, $array2)
{
$result = Array();
array_map(function($item1, $item2) use (&$result)
{
$result[] = $item1;
$result[] = $item2;
}, $array1, $array2);
return $result;
}
This solution works AND it doesn't matter if both arrays are different sizes/lengths:
function array_merge_alternating($array1, $array2)
{
$mergedArray = array();
while( count($array1) > 0 || count($array2) > 0 )
{
if ( count($array1) > 0 )
$mergedArray[] = array_shift($array1);
if ( count($array2) > 0 )
$mergedArray[] = array_shift($array2);
}
return $mergedArray;
}
Try this function:
function arrayMergeX()
{
$arrays = func_get_args();
$arrayCount = count($arrays);
if ( $arrayCount < 0 )
throw new ErrorException('No arguments passed!');
$resArr = array();
$maxLength = count($arrays[0]);
for ( $i=0; $i<$maxLength; $i+=($arrayCount-1) )
{
for ($j=0; $j<$arrayCount; $j++)
{
$resArr[] = $arrays[$j][$i];
}
}
return $resArr;
}
var_dump( arrayMergeX(array(1,3,5,7), array(2,4,6,8)) );
var_dump( arrayMergeX(array('You', 'very'), array('are', 'intelligent.')) );
var_dump( arrayMergeX() );
It works with variable numbers of arrays!
Live on codepad.org: http://codepad.org/c6ZuldEO
if arrays contains numeric values only, you can use merge and sort the array.
<?php
$a = array(1,3,5,7);
$b = array(2,4,6,8);
$merged_array = array_merge($a,$b);
sort($merged,SORT_ASC);
?>
else use this solution.
<?php
function my_merge($array1,$array2)
{
$newarray = array();
foreach($array1 as $key => $val)
{
$newarray[] = $val;
if(count($array2) > 0)
$newarray[] = array_shift($array2)
}
return $newarray;
}
?>
hope this help
Expects both arrays to have the same length:
$result = array();
foreach ($array1 as $i => $elem) {
array_push($result, $elem, $array2[$i]);
}
echo join(' ', $result);
I know about array_intersect_key which returns duplicate keys of the first parameter in any of the following parameters.
However I was wondering which would be the easiest way to find duplicate keys across more than two arrays at once? Does PHP offer such a function or do I need to do it with multiple calls?
Given
$a1 = array('hello'=>1, 'tag'=>1);
$a2 = array('moin'=>1);
$a3 = array('moin'=>1, 'tag'=>1);
Duplicate keys across all three arrays are moin and tag.
I thought so far about calling array_intersect_keys on each possible pair of parameters (in a function accepting a 2-n number of arrays as parameters) but have problems to actually find all possible combinations. And perhaps there is a much more easier way to do this.
Here's a custom function I made which does what you're looking for:
function array_duplicate_keys()
{
$keys = array();
foreach(func_get_args() as $arr)
{
if(!is_array($arr))
{
continue;
}
foreach($arr as $key => $v)
{
if(!isset($keys[$key]))
{
$keys[$key] = -1;
}
$keys[$key]++;
}
}
return array_keys(array_filter($keys));
}
$a1 = array('hello'=>1, 'tag'=>1);
$a2 = array('moin'=>1);
$a3 = array('moin'=>1, 'tag'=>1);
/*
print_r(array_duplicate_keys($a1, $a2, $a3));
Array
(
[0] => tag
[1] => moin
)
*/
I think your idea is good - call it on every possible combination of arrays. Two nested for loops should be enough to get all combinations:
function array_duplicate_keys() {
$arrays = func_get_args();
$count = count($arrays);
$dupes = array();
// Stick all your arrays in $arrays first, then:
for ($i = 0; $i < $count; $i++) {
for ($j = $i+1; $j < $count; $j++) {
$dupes += array_intersect_key($arrays[$i], $arrays[$j]);
}
}
return array_keys($dupes);
}
$a1 = array('hello'=>1, 'tag'=>1);
$a2 = array('moin'=>1);
$a3 = array('moin'=>1, 'tag'=>1);
$all = array($a1, $a2, $a3);
function pair_duplicate_keys($arrays) {
$keys = array();
$result = array();
foreach ($arrays as $array) {
foreach ($array as $key => $value) {
if (!isset($keys[$key])) {
$keys[$key] = 1;
} else {
$result[$key] = 1;
}
}
}
return array_keys($result);
}
print_r(pair_duplicate_keys($all));
Output
Array
(
[0] => moin
[1] => tag
)
All you need is a simple call to array_merge function:
$a = array_merge($a1, $a2, $a3);
print_r($a);
OUTPUT
Array
(
[hello] => 1
[tag] => 1
[moin] => 1
)
Ugly, but does the job:
function array_duplicate_keys() {
return array_keys(array_filter(array_count_values(call_user_func_array('array_merge', array_map('array_keys', func_get_args()))), function ($num) {
return $num > 1;
}));
}
$a1 = array('hello'=>1, 'tag'=>1);
$a2 = array('moin'=>1);
$a3 = array('moin'=>1, 'tag'=>1);
print_r(
array_duplicate_keys($a1, $a2, $a3)
);
Output:
Array
(
[0] => tag
[1] => moin
)