$new_array = array_diff ($array1, $array2,....);
Returns all elements of $array1 which are not present in $array2 ($new_array=$array1 without $array2).
$first=array('a','b','c','d','e');
$second=array('f','c','b');
$result=array_diff($first,$second);
while (list ($key, $val) = each ($result)) {
echo "$key -> $val <br>";
}
Output is here.
0 -> a
3 -> d
4 -> e
Keys of the first index are retained. ( no re-indexing done here)
$first=array('a','b','c','d','e');
$second=array('f','g','h');
$result=array_diff($first,$second);
while (list ($key, $val) = each ($result)) {
echo "$key -> $val
";
}
Output is here
0 -> a
1 -> b
2 -> c
3 -> d
4 -> e
Keys of the first array is retained without any re-indexing.
$first=array('Fruits1' =>'Banana','Fruits2'=>'Mango','Fruits3'=>'Apple');
$second=array('new_fruit1'=> 'Strawberry','new_fruit2'=>'Mango');
$result=array_diff($first,$second);
while (list ($key, $val) = each ($result)) {
echo "$key -> $val <br>";
}
Output is here
Fruits1 -> Banana
Fruits3 -> Apple
For example let us use one array a1 and store text entered by user in a web form after converting the text string to an array. Now to prevent spammers posting URL or posting of some bad words we will develop another array a2 where all negative words we will store. These words we don't want to be present in the first ( a1) array.
$a1=array("first", "second", "third","fourth","fifth");
$a2=array("second","fourth","sixth");
$new_array=array_diff($a1,$a2);
while (list ($key, $val) = each ($new_array)) {
echo "$key -> $val <br>";
}
The output of above code is here
How array_diff() is used to remove elements from file name array
MAZHAR HUSSAIN | 08-08-2010 |
PLEASE SEND ME SIR!DIFFERENCE BETWEEN FUNCTION AND ARRAY? |