two arrays with the same value - php

I have two arrays.
I need to make a foreach where it loops the values that is the same in both arrays. The arrays are not in same order and one of the arrays have more values than the other array.
I could do this.
foreach($array1 as $items1)
{
foreach($array2 as $items2)
{
if($items1 == $items2)
Echo "Match!";
}
}
But that takes a lot of time to load
Edit
I dont get any matches.
Array 1
$array1 = array();
while($fetch = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))
{
$array1[] = array("a" => $fetch['value']);
}
Array 2
$filename = "test.txt";
$fp = #fopen($filename, 'r');
if ($fp) {
$array2 = explode("\n", fread($fp, filesize($filename)));
}
CODE
array_unshift($array2,"b");
$result = array_intersect($array1, $array2);
print_r($result);

You can use array_intersect:
$matches = array_intersect($array1, $array2);

You can use PHP in built function array_intersect()
<?php
$array1 = array("a" => "green", "red", "blue");
$array2 = array("b" => "green", "yellow", "red");
$result = array_intersect($array1, $array2);
print_r($result);
?>
Output
Array
(
[a] => green
[0] => red
)
Note : Returns an array containing all of the values in array1 whose values exist in all of the parameters.

Related

How to merge arrays in PHP with a same value

I want to merge two arrays with the same value -> user_id to one array.
You can see I have two arrays with different objects. I want merge them by user_id to one array with all objects.
For example:
$array1 = [
$array[0]->leads = 5643;
$array[0]->user_id= 15;
$array[0]->sales = 1433;
$array[1]->leads = 3264;
$array[1]->user_id= 9;
$array[1]->sales = 1254;
];
$array2 = [
$array[0]->user_id= 15;
$array[0]->processing = 2300;
$array[0]->deleted = 203;
$array[1]->user_id= 9;
$array[1]->processing = 103;
$array[1]->deleted = 80;
];
The following array is the target.
$result = [
$array[0]->user_id= 15;
$array[0]->processing = 2300;
$array[0]->leads = 5643;
$array[0]->deleted = 203;
$array[0]->sales = 1433;
$array[1]->user_id= 9;
$array[1]->processing = 103;
$array[1]->leads = 3264;
$array[1]->deleted = 80;
$array[1]->sales = 1254;
];
Iterate your array and build the combined array of objects using user_id as the key.
foreach ($array as $entry) {
// if an entry for this user id hasn't been created in the result, add this object
if (!isset($result[$entry->user_id])) {
$result[$entry->user_id] = $entry;
// otherwise, iterate this object and add the values of its keys to the existing entry
} else {
foreach ($entry as $key => $value) {
$result[$entry->user_id]->$key = $value;
}
}
}
Given the additional info you just gave (two separate arrays) the solution is basically the same, just merge the two arrays together first.
foreach (array_merge($array1, $array2) as $entry) { ...
(Working example at https://3v4l.org/ccdQc)
How about array_merge,
<?php
$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$result = array_merge($array1, $array2);
print_r($result);
?>
or array_merge_recursive,
<?php
$ar1 = array("color" => array("favorite" => "red"), 5);
$ar2 = array(10, "color" => array("favorite" => "green", "blue"));
$result = array_merge_recursive($ar1, $ar2);
print_r($result);
?>
Example
$array = [
1 => [
'cost' => '25'
],
2 => [
'blah' => 'test'
]
];
$new_array = array_merge_recursive($array[1], $array[2]);
var_dump($new_array);
Output
array(2) {
["cost"]=>
string(2) "25"
["blah"]=>
string(4) "test"
}
Live Example
Repl
<?php
$array1= array("leads"=> 5643,"user_id"=>15,"sales" =>1433);
$array2= array("user_id"=> 15,"processing" => 2300,"deleted" => 203);
$array= (array_merge($array1,$array2));
print_r($array);
?>

associative array_search not working as expected

Hi I am trying to array_search for associative array in Php but the function isnot working as expected. can anyone help me with this. currently using php version 5.4
<?php
$mainArray = array("array1","array2","array3");
$array1 = array("item"=>"apple","price"=>2);
$array2 = array("item"=>"banana","price"=>3);
$array3 = array("item"=>"carrot","price"=>4);
echo phpversion();
echo "this line ".array_search("apple", array_column($mainArray,'item'));
echo "end";
?>
Problem: In your code $mainArray = array("array1","array2","array3"); you are declaring array of strings not array of arrays.
Change this:
$mainArray = array("array1","array2","array3");
This:
$mainArray = array($array1, $array2, $array3);
And use this $mainArray = array($array1, $array2, $array3) after definition of $array1, $array2, $array3
PHP code: Try this code snippet here
<?php
ini_set('display_errors', 1);
$array1 = array("item" => "apple", "price" => 2);
$array2 = array("item" => "banana", "price" => 3);
$array3 = array("item" => "carrot", "price" => 4);
//should be declared like this and should be after defintion of $array1, $array2, $array3
$mainArray = array($array1, $array2, $array3);
echo "this line " . array_search("apple", array_column($mainArray, 'item'));
?>

Find shared vales in array, put into anothyer array

I have been trying to find the answer to this one with no luck, so if anyone can help I would really appreciate it. is there a function in PHP which can compare 2 arrays and place matching values in a 3rd array? Also I wonder how I could determine if there were any matches or not, like a boolean.
$array1 = array (1,2,3,4);
$array2 = array (1, 2, 7,8);
//I want to have an array like $array3 after comparing $array1
//and $array2.....also I want to know if values were placed in
//$array3 or not.
$array3 = array(1,2);
You could use array_intersect
From the manual:
$array1 = array("a" => "green", "red", "blue");
$array2 = array("b" => "green", "yellow", "red");
$result = array_intersect($array1, $array2);
Which produces:
Array
(
[a] => green
[0] => red
)
If you want to check if there were matches you can do:
empty($result) //true if empty, meaning no matches
Manual entry is here. I borrowed the first example.
$array1 = array (44,2,3,4);
$array2 = array (44,2,7,8);
//I want to have an array like array 3 after comparing $array1
//and $array2.....also I want to know if values were placed in
//$array3 or not.
$array3 = array(44,2);
$result = array_intersect($array1, $array2);
if ($result){
$match = true;
echo $result [0];
}
else{
$match = false;
}
if ($match === true){
// Do something
}
else{
//do something else
}

PHP array_intersect case-insensitive and ignoring tildes

Is there any function similar to "array_intersect" but it is in mode case-insensitive and ignoring tildes?
The array_intersect PHP function compares array elements with === so I do not get the expected result.
For example, I want this code :
$array1 = array("a" => "gréen", "red", "blue");
$array2 = array("b" => "green", "yellow", "red");
$result = array_intersect($array1, $array2);
print_r($result);
Outputs gréen and red. In default array_intersect function just red is proposed (normal cause ===).
Any solution ?
Thank you in advance
$result = array_intersect(array_map('strtolower', $array1), array_map('strtolower', $array2));
<?php
function to_lower_and_without_tildes($str,$encoding="UTF-8") {
$str = preg_replace('/&([^;])[^;]*;/',"$1",htmlentities(mb_strtolower($str,$encoding),null,$encoding));
return $str;
}
function compare_function($a,$b) {
return strcmp(to_lower_and_without_tildes($a), to_lower_and_without_tildes($b));
}
$array1 = array("a" => "gréen", "red", "blue");
$array2 = array("b" => "green", "yellow", "red");
$result = array_uintersect($array1, $array2,"compare_function");
print_r($result);
output:
Array
(
[a] => gréen
[0] => red
)

What is the most efficient way to remove all the elements of one array from another array?

I have two arrays, array A contains a long list with some elements I want to remove. Array B is the full list of those elements that I wish to remove from array A.
What is the most efficient way to achieve this?
array_diff is the obvious answer, but since you've asked for the most efficient way, here's a test
$big = range(1, 90000);
$remove = range(500, 600);
$ts = microtime(true);
$result = array_diff($big, $remove);
printf("%.2f\n", microtime(true) - $ts);
$ts = microtime(true);
$map = array_flip($remove);
$result = array();
foreach($big as $e)
if(!isset($map[$e]))
$result[] = $e;
printf("%.2f\n", microtime(true) - $ts);
prints on my machine
0.67
0.03
So the simple loop with a hash-based lookup is approximately 20 times faster than array_diff.
Use array_diff()
In the manual it gives for array_dif() this exaple:
<?php
$array1 = array("a" => "green", "red", "blue", "red");
$array2 = array("b" => "green", "yellow", "red");
$result = array_diff($array1, $array2);
print_r($result);
?>
Outputs:
Array
(
[1] => blue
)
Returns an array containing all the
entries from array1 that are not
present in any of the other arrays.

Categories