note 36880 modified in function.array-diff-assoc by aidan

From: Date: Wed, 09 Jun 2004 10:15:54 +0000
Subject: note 36880 modified in function.array-diff-assoc by aidan
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-70569@lists.php.net to get a copy of this message
array_diff_assoc() requires that both the key and the value pairs match. To match based on keys only, try this function. <?php function array_diff_keys($source, $diff) { $res = $source; foreach ($diff as $key=>$data) { unset($res[$key]); } return $res; } // Example $a = array('a' => '1', 'b' => '2', 'c' => '3'); $b = array('a' => '2', 'b' => '2', 'e' => '4'); // Yields array('a' => '1', 'c' => '3') // Note that the 'a' index is not removed (as one might expect) $c = array_diff_assoc($a, $b); // Yields array('c' => '3') $d = array_diff_keys($a, $b); ?> --was-- As mentioned earlier, this function requires that both the key and the value match. To match (and remove) based on keys only, try this function. <?php function array_diff_keys($source, $diff) { $res = $source; foreach ($diff as $key=>$data) { unset($res[$key]); } return $res; } // example $a = array('a' => '1', 'b' => '2', 'c' => '3'); $b = array('a' => '2', 'b' => '2', 'e' => '4'); // Yields array('a' => '1', 'c' => '3') // Note that the 'a' index is not removed (as one might expect) $c = array_diff_assoc($a, $b); // Yields array('c' => '3') $d = array_diff_keys($a, $b); ?> http://www.php.net/manual/en/function.array-diff-assoc.php

« previous php.notes (#70569) next »