phparraysmultidimensional-array

Check if a flat associative array exists as a whole row in another 2d array


I'm having problems comparing these arrays.

In a nutshell I want to check if $tid_and_date_arr exists within $curr_vals. (Have a look. It does, obviously.)

My logic is flawed, however, as the second time during the loop, $tid_and_date_arr != $value[1] so the value isn't skipped.

What am I missing? Another loop inside the loop?

$curr_vals = array(
    array('tid' => 22, 'date' => 1497250800),
    array('tid' => 22, 'date' => 1497337200)
);
    
$tid_and_date_arr = array('tid' => 22, 'date' => 1497250800);

foreach ($curr_vals as $value) {
    if ($tid_and_date_arr == $value) {
        // skip these values as we've already saved them
        continue;
    } else {
       // save these values as they are new
    }
}

Solution

  • What is wrong with good old array_search?

    $curr_vals = array(array('tid' => 22, 'date' => 1497250800), array('tid' => 22, 'date' => 1497337200));
    //$tid_and_date_arr = array('tid' => 22, 'date' => 1497250800); -- this will output 0
    $tid_and_date_arr = array('tid' => 22, 'date' => 1497337200);
    
    $result = array_search($tid_and_date_arr, $curr_vals);
    
    print_r($result);
    

    This will output the key of the subarray you're looking for:

    1