2

Below is an example of two arrays that I am trying to compare. What I am trying to do is compare is check if any values from array2 exist in array1 and return the difference.

$array1 = ["8:00 am","8:30 am","10:00 am","11:00 am","11:45 am","1:30 pm","2:30 pm","3:30 pm","4:15 pm", "8:00 am","8:30 am","10:15 am","11:30 am","1:00 pm","2:30 pm","3:45 pm","8:00 am"];

$array2 = ["08:00 am","08:45 am","09:30 am","10:15 am","11:00 am","11:45 am","12:30 pm","01:15 pm", "02:00 pm", "02:45 pm","03:30 pm","04:15 pm","05:00 pm"];


$result = array_diff_assoc($array2,$array1);

results when var_dump:

array(13) {
  [0]=>
  string(8) "08:00 am"
  [1]=>
  string(8) "08:45 am"
  [2]=>
  string(8) "09:30 am"
  [3]=>
  string(8) "10:15 am"
  [4]=>
  string(8) "11:00 am"
  [5]=>
  string(8) "11:45 am"
  [6]=>
  string(8) "12:30 pm"
  [7]=>
  string(8) "01:15 pm"
  [8]=>
  string(8) "02:00 pm"
  [9]=>
  string(8) "02:45 pm"
  [10]=>
  string(8) "03:30 pm"
  [11]=>
  string(8) "04:15 pm"
  [12]=>
  string(8) "05:00 pm"
}
Dark Knight
  • 6,116
  • 1
  • 15
  • 37

2 Answers2

1

PHP will check difference by directly comparing strings and here definitely we don't have inputs in same format.

Solution:

  • First change $array1 to standard format and then find the difference.
  • To find difference between these arrays, you need array_diff not array_diff_assoc.

array_diff

  • Returns an array containing all the entries from array1 that are not present in any of the other arrays

array_diff_assoc

  • Computes the difference of arrays with additional index check
$formatted_array = array_map(function($time){
    return date("h:i a", strtotime($time) );
}, $array1);

$result = array_diff($array2, $formatted_array);
Dark Knight
  • 6,116
  • 1
  • 15
  • 37
0

agh, dummy me. the arrays are not the same. Example:

["08:00 am"] is not the same as ["8:00 am"]

had to convert my array and add 0. Then it worked.