Current Location: Home> Latest Articles> Use array_diff() to process string arrays with special characters

Use array_diff() to process string arrays with special characters

M66 2025-06-06

In PHP, array_diff() is a very practical function to compare two or more arrays and return values ​​that exist in the first array but not in other arrays. When we process string arrays containing special characters (such as @ , # , % , &, etc.), we can also use this function to easily implement differential set comparison.

This article will introduce the basic usage of array_diff() and use examples to show how to deal with string arrays containing special characters.

1. The basic syntax of array_diff()

 array_diff(array $array1, array ...$arrays): array

This function compares $array1 with one or more arrays followed and returns a value that only exists in $array1 and does not appear in other arrays.

Note: Comparison is based on values ​​and uses loose comparisons (==) and does not compare key names.

2. The problem of array difference set containing special characters

Suppose you have two arrays with the following content:

 $array1 = ['apple', 'banana', 'cherry@', 'date#', 'egg&'];
$array2 = ['banana', 'date#', 'fig$', 'grape'];

You want to find out the elements that exist in $array1 but do not exist in $array2 , even if they contain special characters.

You can use array_diff() directly, because PHP does not do special processing for special characters when comparing strings, and can still compare them normally.

3. Sample code

 <?php

$array1 = ['apple', 'banana', 'cherry@', 'date#', 'egg&'];
$array2 = ['banana', 'date#', 'fig$', 'grape'];

$result = array_diff($array1, $array2);

echo "Differential results:\n";
print_r($result);

// If you want to generate one of these difference elements URL Query parameter form:
$queryString = http_build_query(['items' => array_values($result)]);

echo "\nYou can use the following link to access the query result page:\n";
echo "https://m66.net/show_diff.php?$queryString";

?>

The output result is:

 Differential results:
Array
(
    [0] => apple
    [2] => cherry@
    [4] => egg&
)

You can use the following link to access the query result page:
https://m66.net/show_diff.php?items%5B0%5D=apple&items%5B1%5D=cherry%40&items%5B2%5D=egg%26

4. Things to note

  1. Special characters do not affect how array_diff() works.

  2. If you need to deal with comparisons with case differences, you can first uniformly process the elements in the array (such as using strtolower() ).

  3. If you get a string array from user input, remember to do basic filtering and escape to prevent injection attacks and other problems.

5. Practical application scenarios

  • Compare two data sets from different sources (such as database and user uploaded data).

  • Identify unsynced data records.

  • Implement keyword filtering function, find input content that has not been covered by the filtered vocabulary library, etc.