Search code examples
phparray-difference

PHP array_diff_key() is empty but should not


I query a series of tables in order to print these, and I want to print all keys of each table even if the values are empty, but a specific set of keys which are the same for each table shall not be printed.

My query and fetch of the result in an array for one table:

$stmt = $db_conn->prepare("SELECT * FROM table;");
$stmt->execute();
$array = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();

var_export($array);returns:

array ( 0 => array ( 'a' => '1', 'b' => '2018-12-21', 'c' => '', 'd' => '', ), )

I prepared a list of bad keys in an array:

var_export($bad_keys);returns:

array ( 0 => array ( 'a' => '1', 'b' => '2019-01-05', ), )

For each table I want to exclude the bad keys {a, b} from the query result in $array by use of array_diff_key():

$array_new = array_diff_key($array, $bad_keys); 

var_dump($array_new); returns empty:

array(0) { }.

$array_new should have the keys {'c', 'd'} but it has not. I don't see a mistake in my code. Please help.


Solution

  • My mistake: In array_diff_key() I compared two multidimensional arrays without writing the index [0] for each array to be compared.

    Solution: I added the index [0] to each array to be compared, and additionally I created an array from the result of array_diff_key()

    $array = array( 0 => 
         array( 
            'a' => '', 
            'b' => '', 
            'c' => '', 
            'd' => '', 
        ), 
    );
    
    $bad_keys = array( 0 => 
         array( 
            'a' => '', 
            'b' => '', 
        ), 
    );
    
    $array_new = array( array_diff_key( $array[0], $bad_keys[0] ));
    
    var_export( $array_new );
    

    now returns the desired result:

    array( 0 => 
         array( 
            'c' => '', 
            'd' => '', 
        ), 
    );