I am having two arrays of key-value pairs.
Arrays as follows:
$array1 = ["a" => 2, "b" => 3, "c" => 1, "d" => 2];
$array2 = ["c" => 1, "d" => 1, "a" => 2, "b" => 3, "x" => 4, "z" => 1];
Problem Statement
I need to find the count of the number of keys of array1 present in array2 having the same value.
Example
Count will be 3 as keys a, b, and c of array1 are present in array2 and having same values 2, 3, and 1 respectivily.
Tried method
foreach($array1 as $key => $value){
if($array2.$key === $array1.$key){
if($array2[$value] === $array1[$value]){
$matchCount++;
}
}
}
NOTE: I am not sure about accessing the keys from the array object, so using dot(.), somehow I am getting the count, but not correct count.
<?php
$array1 = ["a" => 2, "b" => 3, "c" => 1, "d" => 2];
$array2 = ["c" => 1, "d" => 1, "a" => 2, "b" => 3, "x" => 4, "z" => 1];
$count = 0;
foreach($array1 as $key => $value){
$array_2_value = $array2[$key] ?? null;
if($array_2_value !== null && $array_2_value === $value) $count++;
}
echo $count;
Demo: https://3v4l.org/BREbg
You can just loop over $array1 and check if the key exists in $array2 with the same value. If yes, we increment count. You can make use of null coalescing operator ?? to check if the $key exists in $array2 or not.
function countSameKeyAndValues(array $array1, array $array2): int
{
$sameKeys = array_keys(array_intersect($array1, $array2));
$count = 0;
foreach ($sameKeys as $key) {
if ($array1[$key] === $array2[$key]) {
$count++;
}
}
return $count;
}
You can loop over the $array1 using foreach loop.
Then you can check for the values of $array2 using the key for $array1.
Then if value exist for that key, you can check if value is same at that of $array1
<?php
$array1 = ["a" => 2, "b" => 3, "c" => 1, "d" => 2];
$array2 = ["c" => 1, "d" => 1, "a" => 2, "b" => 3, "x" => 4, "z" => 1];
$count = 0;
foreach($array1 as $key => $value){
$array2Value = $array2[$key] ?? null;
if($array2Value !== null && $array2Value === $value)
$count++;
}
echo $count;
Related
I have two arrays:
$a = ['0' => 1, '1' => 2, '2' => 3]
$b = ['0' => 4, '1' => 5, '2' => 6]
I want to create a new array like this:
[
['a' => 1, 'b' => '4'],
['a' => '2', 'b' => '5']
]
I have tried using array_merge and array_merge_recursive, but I wasn't able to get the right results.
$data = array_merge_recursive(array_values($urls), array_values($id));
You have to apply array_map() with custom function:
$newArray = array_map('combine',array_map(null, $a, $b));
function combine($n){
return array_combine(array('a','b'),$n);
}
print_r($newArray);
Output:-https://3v4l.org/okML7
Try this one
$c = array_merge($a,$b)
$d[] = array_reduce($d, 'array_merge', []);
It will merge the two array and reduce and remerge it.
You can use foreach to approach this
$a = ['0' => 1, '1' => 2, '2' => 3];
$b = ['0' => 4, '1' => 5, '2' => 6];
$res = [];
$i = 0;
$total = 2;
foreach($a as $k => $v){
$res[$i]['a'] = $v;
$res[$i]['b'] = $b[$k];
$i++;
if($i == $total) break;
}
The idea is to have an array $ab = ['a','b'] and a array from your both arrays like this $merged_array = [[1,4],[2,5],[3,6]]. Now we can combine array $ab with each element of $merged_array and that will be the result we need.
$first = ['0' => 1, '1' => 2, '2' => 3];
$second = ['0' => 4, '1' => 5, '2' => 6];
$merged_array = [];
for($i=0;$i<count($first);$i++)
{
array_push($merged_array,[$first[$i],$second[$i]]);
}
$final = [];
$ab = ['a','b'];
foreach($merged_array as $arr)
{
array_push($final,array_combine($ab, $arr));
}
print_r($final);
All earlier answers are working too hard. I see excessive iterations, iterated function calls, and counter variables.
Because there are only two arrays and the keys between the two arrays are identical, a simple foreach loop will suffice. Just push associative arrays into the result array.
Code: (Demo)
$a = ['0' => 1, '1' => 2, '2' => 3];
$b = ['0' => 4, '1' => 5, '2' => 6];
$result = [];
foreach ($a as $k => $v) {
$result[] = ['a' => $v, 'b' => $b[$k]];
}
var_export($result);
Output:
array (
0 =>
array (
'a' => 1,
'b' => 4,
),
1 =>
array (
'a' => 2,
'b' => 5,
),
2 =>
array (
'a' => 3,
'b' => 6,
),
)
Is there built-in function, or shorter way to extract elements into new array, as described here?
<?php
function arr_slice ($arr, $keys) {
$ret = array();
foreach ($keys as $k) { $ret[$k] = $arr[$k]; }
return $ret;
}
$array = array(
"a" => 1,
"b" => 2,
"c" => 3,
"d" => 4,
);
var_export(
arr_slice($array, array("x","d","b"))
);
output (key order matters)
array (
'x' => NULL,
'd' => 4,
'b' => 2,
)
I have this multidimensional array:
$arr = [
2 => ["a", "b", "c"],
5 => ["j", "k", "l"],
9 => ["w", "x", "y", "z"]
];
For which I'd like to create a new index array like this one:
$index = [
"a" => 2,
"b" => 2,
"c" => 2,
"j" => 5,
"k" => 5,
"l" => 5,
"w" => 9,
"x" => 9,
"y" => 9,
"z" => 9
]
I couldn't find any PHP function that appears to do that, but I'm sure there is one. Or maybe there's some known code that does this efficiently?
$index = array();
foreach ($arr as $k => $a) {
foreach ($a as $v) {
$index[$v] = $k;
}
}
I have 2 * array and I want to merge them, but each of theme have some NULL rows.
$a = array(
'a' => NULL,
'b' => 1,
'c' => 1
);
$b = array(
'a' => 1,
'b' => NULL,
'c' => 1
);
So, code:
$c = array_merge($a,$b);
Will give $c:
array {
'a'=> 1
'b'=> NULL
'c'=>1
}
Is there build in or simple way to do margin ($a,$b) like following, but now $a is overwritten for every same index from $b. I want $b to be overwritten by $a index if $b index is null - in example $b['b'] should be overwritten from $a
All NULL rows should be filled if possible.
I think you can use array_filter function to remove null values in both array and then merge them
$a = array(
'a' => NULL,
'b' => 1,
'c' => 1
);
$b = array(
'a' => 1,
'b' => NULL,
'c' => 1
);
$b = array_filter($b);
$a = array_filter($a);
$c = array_merge($a, $b);
var_dump($c);
This will output
array(3) {
["b"]=> int(1)
["c"]=> int(1)
["a"]=> int(1)
}
LIVE SAMPLE
As side note i would add that using array_filter without second parameter will end up in deleting all NULL values as well as EMPTY array etc. If you want to only remove NULL values so you will need to use array_filter($yourarray, 'strlen');
EDITED
If you want to preserve NULL if both arrays have it with the same key and supposing that both arrays have same number of keys/values, then you will need to loop inside your array and build a new array preserving NULL where you need
$a = array(
'a' => NULL,
'b' => 1,
'c' => 1,
'd' => NULL
);
$b = array(
'a' => 1,
'b' => NULL,
'c' => 1,
'd' => NULL,
);
$c = array();
foreach($a as $key => $val)
{
if($key == NULL && $b[$key] == NULL)
{
$c[$key] = $val;
} else if($key != NULL && $b[$key] == NULL) {
$c[$key]= $val;
} else if($key != NULL && $b[$key] != NULL) {
$c[$key]= $b[$key];
} else {
$c[$key]= $b[$key];
}
}
var_dump($c);
This will output
array (size=4)
'a' => int 1
'b' => int 1
'c' => int 1
'd' => NULL
LIVE SAMPLE
I would do it with a simple one liner like this:
$c = array_filter($b) + array_filter($a) + array_fill_keys(array_keys($b),null);
This would preserve all keys and values of $b except where falsey in which case they will be either replaced with values from $a or as a last resort replaced with null.
When merging arrays with the + operator the order in which they appear from left to right equates to the precedence. So the leftmost position will hold it's value unless the key does not exist.
You can also reverse the order and use array_merge(), but for me it's harder on the eyes:
$c = array_merge(array_fill_keys(array_keys($b),null) + array_filter($a) + array_filter($b));
None of these answers address merging two arrays that may have different keys, which is what lead me to this SO post. It happens to actually be pretty straight forward fortunately:
function arrayMergeIfNotNull($arr1, $arr2) {
foreach($arr2 as $key => $val) {
$is_set_and_not_null = isset($arr1[$key]);
if ( $val == NULL && $is_set_and_not_null ) {
$arr2[$key] = $arr1[$key];
}
}
return array_merge($arr1, $arr2);
}
Now, merging these two arrays:
$a = array('a' => NULL, 'b' => 1, 'c' => 1, 'd' => NULL, 'z' => 'zebra');
$b = array('a' => 1, 'b' => NULL, 'c' => 1, 'd' => NULL, 'f' => 'frank');
with:
var_dump(arrayMergeIfNotNull($a, $b));
will produce:
array (size=6)
'a' => int 1
'b' => int 1
'c' => int 1
'd' => NULL
'z' => 'zebra'
'f' => 'frank'
Note this answer also solves the problem of two arrays with the same keys.
then you have to pass $b as the first parameter
$c = array_merge($b,$a);
you can use this function
function mergeArray($array1, $array2)
{
$result = array();
foreach ($array1 as $key=>$value)
{
$result[$key] = $value;
}
foreach ($array2 as $key=>$value)
{
if (!isset($result[$key] || $result[$key] == null)
{
$result[$key] = $value;
}
}
return $result;
}
If you need to preserve keys that have a value of NULL in both arrays, you can use a custom function that ignores those entries from the second array if (and only if) there is a corresponding non-NULL entry in the first array. It would look like this:
function arrayMergeIgnoringNull($arr1, $arr2) {
$new2 = array();
forEach ($arr2 as $key => $value) {
if (($value !== NULL) || !isSet($arr1[$key])) {
$new2[$key] = $value;
}
}
return array_merge($arr1, $new2);
}
$c = arrayMergeIgnoringNull($a, $b);
See, also, this short demo.
can you give me examples of using array() function ?
There are plenty of examples in the manual:
http://php.net/manual/en/language.types.array.php
more specifically:
http://www.php.net/manual/en/function.array.php
$somearray = array();
$somearray[] = 'foo';
$somearray[] = 'bar';
$someotherarray = array(1 => 'foo', 2 => 'bar');
var_dump($somearray);
echo $someotherarray[2];
$a = array(1, 'test'=>2,'testing'=>'yes');
foreach($a as $key => $value) {
echo $key . ' = ' . $value . '<br />';
}
Even easier to see the output...
print_r($a);
$arr = array(1, 2, 3, 4, 5);
To loop over each element in the array:
foreach($arr as $val) {
print "$var\n";
}
One interesting thing to note about PHP arrays is that they are all implemented as associative arrays. You can specify the key if you want, but if you don't, an integer key is used, starting at 0.
$array = array(1, 2, 3, 4, 5);
is the same as (with keys specified):
$array = array(0 => 1, 1 => 2, 2 => 3, 3 => 4, 4 => 5);
is the same as:
$array = array('0' => 1, '1' => 2, '2' => 3, '3' => 4, '4' => 5);
Though, if you want to start the keys at one instead of zero, that's easy enough:
$array = array(1 => 1, 2 => 2, 3 => 3, 4 => 4, 5 => 5);
Though if you don't specify the key value, it takes the highest key and adds one, so this is a shortcut:
$array = array(1 => 1, 2, 3, 4, 5);
The key (left side) can only be an integer or string, but the value (right side) can be any type, including another array or an object.
Strings for keys:
$array = array('one' => 1, 'two' => 2, 'three' => 3, 'four' => 4, 'five' => 5);
Two easy ways to iterate through an array are:
$array = array('one' => 1, 'two' => 2, 'three' => 3, 'four' => 4, 'five' => 5);
foreach($array as $value) {
echo "$value\n";
}
foreach($array as $key => $value) {
echo "$key=$value\n";
}
To test to see if a key exists, use isset():
if (isset($array['one'])) {
echo "$array['one']\n";
}
To delete a value from the array, use unset():
unset($array['one']);