Get only required arrays in php - php

I am trying to get only required keys for an array from another array as below.
$list = array();
$arrKeys = array("id", "name");
foreach ($_SESSION['bArray'] as $i => $m) {
if(count(array_intersect(array_keys($m), $arrKeys)) > 0) {
$list[$i] = $m;
}
}
But for the $list, it always contains $m. How can I solve this?

If you change $arrKeys to have keys (rather than values) that match those you wish to keep, you can use array_intersect_key to do what you want:
$list = array();
$arrKeys = array("id" => 0, "name" => 0);
foreach ($_SESSION['bArray'] as $i => $m) {
$intersect = array_intersect_key($m, $arrKeys);
if (count($intersect)) {
$list[$i] = $intersect;
}
}
Demo on 3v4l.org

Related

Array comparison and re-order in PHP

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);
?>

How to combine three arrays without using array_merge or array_combine in php

I want to combine three arrays into one
I am expecting like output are using array_combine or array_merge
Likes
friends,
usa,
usa2,
..,
..,
so.on..,
$array1 = array('likes', 'friends', 'USA');
$array2 = array('USA2', 'lools', 'tools');
$array3 = array('USA3', 'Awesome', 'lop');
$output = $array1+$array2+$array3;
echo "<pre>";
print_r($output);
echo "</pre>";
But here i am getting output as
likes,
friends,
USA
In PHP 5.6+ You can also use ... when calling functions to unpack an array or
Traversable variable or literal into the argument list:
$array1 = array('likes', 'friends', 'USA');
$array2 = array('USA2', 'lools', 'tools');
$array3 = array('USA3', 'Awesome', 'lop');
array_push($array1, ...$array2, ...$array3);
echo "<pre>";
print_r($array1);
echo "</pre>";
demo
check this out custom function for array push
<?php
$array1 = array('likes', 'friends', 'USA');
$array2 = array('USA2', 'lools', 'tools');
$array3 = array('USA3', 'Awesome', 'lop');
function push($array1,$array2){
$return = array();
foreach($array1 as $key => $value){
$return[] = $value;
}
foreach($array2 as $key => $value){
$return[] = $value;
}
return $return;
}
$array = push($array1,$array2);
$array = push($array,$array3);
print_r($array);
If you want to have an array of arrays, each element at a given index having the values of the three arrays at the respecting index, then:
$length = count($array1);
$result = array();
for ($index = 0; $index < $length; $index++) {
$result[]=array($array1[$index], $array2[$index], $array3[$index]);
}
If you simply want to put all items into a new array, then:
$result = array();
for ($index = 0; $index < count($array1); $index++) {
$result[]=$array1[$index];
}
for ($index = 0; $index < count($array2); $index++) {
$result[]=$array2[$index];
}
for ($index = 0; $index < count($array3); $index++) {
$result[]=$array3[$index];
}
Use Array Merge
$array1 = array('likes', 'friends', 'USA');
$array2 = array('USA2', 'lools', 'tools');
$array3 = array('USA3', 'Awesome', 'lop');
$output = array_merge($array1,$array2,$array3);
echo "<pre>";
print_r($output);
echo "</pre>";

PHP Merging arrays with for loops without using array_merge function

I am learning more about for loops and would like to see how do you merge arrays using only for loops and not using built-in PHP functions such as array_merge().
I know you can use foreach to do this, but how would this work using only for loops and not foreach?
foreach example:
$array1 = ['judas', 'john', 'michael'];
$array2 = ['fernando', 'jsamine', 'sam', 'walter'];
$array3 = ['judas', 'john', 'mike', 'steve'];
foreach ([$array1, $array2, $array3] as $arr) {
foreach ($arr as $values) {
...
}
}
Yes, you can do this using just for loops.
$array1 = ['judas', 'john', 'michael'];
$array2 = ['fernando', 'jsamine', 'sam', 'walter'];
$array3 = ['judas', 'john', 'mike', 'steve'];
$all_arrays = [$array1, $array2, $array3];
$merged = [];
for ($i = 0; $i < 3; $i++) {
$arr = $all_arrays[$i];
$x = count($arr);
for ($j=0; $j < $x; $j++) {
// Using the value as the key in the merged array ensures
// that you will end up with distinct values.
$merged[$arr[$j]] = 1;
}
}
// You could use array_keys() to do get the final result, but if you
// want to use just loops then it would work like this:
$final = [];
$x = count($merged);
for ($i=0; $i < $x; $i++) {
$final[] = key($merged);
next($merged);
}
var_dump($final);
key() and next() ARE php functions. But I really do not know of a way to get to the keys without using either foreach or some php function.
Iterate each array on its own:
foreach($array2 as $v)
if(!in_array($v, $array1))
$array1[] = $v;
foreach($array3 as $v)
if(!in_array($v, $array1))
$array1[] = $v;
Or simply use array_merge() - there is no reason for do not do it.
$a=array('1','2','3','4','5');
$b=array('a','b','c','d','e');
$c=count($b);
for($i=0; $i<$c; $i++)
{
$a[]=$b[$i]; // each element 1 by 1 store inside the array $a[]
}
print_r($a);
function arrayMerge(array $arrays) {
$mergeArray = [];
foreach ($arrays as $key => $array) {
foreach($array as $finalArray) {
$mergeArray[] = $finalArray;
}
}
return $mergeArray;
}
$array1 = [
'Laravel', 'Codeigniter', 'Zend'
];
$array2 = [
'Node js', 'Vue js', 'Angular js'
];
$array3 = [
'Python', 'Django', 'Ruby'
];
print_r(arrayMerge([$array1, $array2, $array3]));
$arr1 = array(1,2,3,4,5);
$arr2 = array(2,5,6,7,8);
$allval = array();
foreach($arr2 as $key=>$val){
$arr1[] = $val;
}
foreach($arr1 as $k=>$v){
if(!in_array($v,$allval)){
$allval[] = $v;
}
}
echo "<pre>"; print_R($allval);

Merge every other array php

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);

How to get the duplicate keys of multiple arrays?

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
)

Categories