1

I have 2 arrays of dates. I need the most efficient way to build a third array of dates that consists of only the dates that are the same from the 2 arrays of dates.

For example:

List of Dates #1:
2017-01-01
2017-01-02
2017-01-03
2017-02-01
2017-02-02
2017-09-09

List of Dates #2:
2017-01-01
2017-02-01
2017-03-01
2017-04-01

So array 3 should be:
2017-01-01
2017-02-01
1

3 Answers 3

2

You are looking for array_intersect:

Working Demo: https://eval.in/862254

$array1 = array("2017-01-01", "2017-01-01" ,"2017-01-02","2017-01-03","2017-02-01", "2017-02-02","2017-09-09");

$array2 = array("2017-01-01","2017-02-01","2017-03-01","2017-04-01");
$result = array_intersect(array_unique($array1), $array2);
echo "<pre>";
print_r($result);

Output:

Array
(
    [0] => 2017-01-01
    [3] => 2017-02-01
)

Note

array_intersect Returns an array containing all of the values in $array1 whose values exist in all of the parameters. So if your $array1 is having duplicate data then resultant array also have duplicate values.

I have added array_unique to overcome that situation.

Sign up to request clarification or add additional context in comments.

4 Comments

any way to prevent duplicate entries? that's the kicker for me when I tried this. The output must not contain duplicate entries even if there are multiple overlapping dates.
Glad to help you :)
Do you also know how I can make reference to the first, second, etc values in this array if they are labelled like your output where they may not be [0], [1], [2], etc?
for example a for loop would not be able to cycle through the records using an increment like $i... for ($i = 0; $i <= count($array) - 1; $i++) {... because the out has varying labelling numbers, in the case of your output 0 then 3
0

Maybe array_intersect() ?

$array1 = array ("a" => "green", "red", "blue");
$array2 = array ("b" => "green", "yellow", "red");
$result = array_intersect ($array1, $array2);

result

Array
(
    [a] => green
    [0] => red
)

Comments

0

Try this

function myfunction($a,$b)
{
if ($a===$b)
  {
  return 0;
  }
  return ($a>$b)?1:-1;
}

$a1=array("a"=>"red","b"=>"green","c"=>"blue","yellow");
$a2=array("A"=>"red","b"=>"GREEN","yellow","black");
$a3=array("a"=>"green","b"=>"red","yellow","black");

$result=array_uintersect($a1,$a2,$a3,"myfunction");
print_r($result);

Result:

Array ( [a] => red [0] => yellow )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.