Home  >  Article  >  Backend Development  >  How to remove duplicate values ​​from text in php

How to remove duplicate values ​​from text in php

PHPz
PHPzOriginal
2023-03-31 10:05:55851browse

When writing programs in PHP, you often encounter situations where you need to remove duplicate values ​​from text. Removing duplicate values ​​from text can greatly improve the efficiency and accuracy of the program and avoid double calculations and erroneous statistics. This article will introduce how to use PHP to remove duplicate values ​​​​from text.

1. Removing duplicate values ​​from an array in PHP

In PHP, you can use the array_unique() function to remove duplicate values ​​from an array. This function accepts an array as a parameter and returns an array with duplicate values ​​removed. The following is a sample code:

$array = array("apple", "banana", "orange", "apple", "pear", "orange");
$result = array_unique($array);
print_r($result);

The output result is:

Array
(
    [0] => apple
    [1] => banana
    [2] => orange
    [4] => pear
)

2. Remove duplicate values ​​from strings in PHP

For strings, you can Convert the string into an array, and then use the array_unique() function to remove duplicate values. The following is a sample code:

$string = "hello world";
$array = str_split($string);
$result = array_unique($array);
print_r(implode("", $result));

The output result is:

helowrd

3. Remove duplicate values ​​​​in files in PHP

When processing files, you can use PHP The file reading and writing function reads the contents of the file into a string, then converts the string into an array and uses the array_unique() function to remove duplicate values, and finally writes the result back to the file. The following is a sample code:

$file = "data.txt";
$content = file_get_contents($file);
$array = explode("\n", $content);
$result = array_unique($array);
file_put_contents($file, implode("\n", $result));

The above code will read the content from a file named "data.txt", remove duplicate values, and finally write the results back to the same file.

Summary:

This article introduces how to use PHP to remove duplicate values ​​​​from text. For arrays and strings, you can directly use the array_unique() function to remove duplicate values; for files, you can use the file read and write functions to read, process, and write back data. These methods can greatly simplify the program processing process and improve the operating efficiency and accuracy of the program.

The above is the detailed content of How to remove duplicate values ​​from text in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn