Jeff Sayers
Jeff Sayers

Reputation: 127

How to create new array of dates from existing arrays of dates in PHP?

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

Upvotes: 1

Views: 61

Answers (3)

Jigar Shah
Jigar Shah

Reputation: 6223

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.

Upvotes: 2

Salim Ibrohimi
Salim Ibrohimi

Reputation: 1391

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 )

Upvotes: 0

Teaminds
Teaminds

Reputation: 1

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
)

Upvotes: 0

Related Questions