note 18894 modified in function.array-diff by vrana

From: Date: Tue, 17 Aug 2004 13:57:44 +0000
Subject: note 18894 modified in function.array-diff by vrana
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-79912@lists.php.net to get a copy of this message
For those who are looking how to substract one array for another: you cannot use the "-" operator !!! But you can use this function: <?php function array_minus_array($a, $b) { $c=array_diff($a,$b); $c=array_intersect($c, $a); return $c; } ?> So, for example: <?php $a[]="a"; $a[]="b"; $a[]="c"; $b[]="a"; $c=array_minus_array($a,$b); var_dump($c); ?> Prints out: array(2) { [1]=> string(1) "b" [2]=> string(1) "c" } which is $a-$b, as we wanted. PD: you may also do a foreach ... if $a in_array $b ... but this is much more elegant !!! Credits to A.Atala "mandrake", who knows everything about mathematic. --was-- For those who are looking how to substract one array for another: you cannot use the "-" operator !!! But you can use this function: function array_minus_array($a, $b) { $c=array_diff($a,$b); $c=array_intersect($c, $a); return $c; } So, for example: $a[]="a"; $a[]="b"; $a[]="c"; $b[]="a"; $c=array_minus_array($a,$b); var_dump($c); Prints out: array(2) { [1]=> string(1) "b" [2]=> string(1) "c" } which is $a-$b, as we wanted. PD: you may also do a foreach ... if $a in_array $b ... but this is much more elegant !!! Credits to A.Atala "mandrake", who knows everything about mathematic. http://php.net/manual/en/function.array-diff.php

« previous php.notes (#79912) next »