Home > Backend Development > PHP Problem > How to find non-existent elements in php array

How to find non-existent elements in php array

PHPz
Release: 2023-04-19 14:57:15
Original
683 people have browsed it

In PHP, array is a very common data type. When working with data, you often need to find missing parts of it. This article will show you how to find elements that are not present in an array.

Suppose we have an array with many elements as shown below:

$array1 = array('apple', 'banana', 'orange', 'grape', 'kiwi');
Copy after login

We want to find out the missing elements in the following array:

$array2 = array('apple', 'pear', 'grape');
Copy after login

In this case, The following elements should be found:

pear
Copy after login

To find elements that do not exist in $array1, you can use the PHP function array_diff(). This function removes all elements present in the second array from the first array. This will return all elements in the first array that are not contained in the second array.

The sample code is as follows:

$missing = array_diff($array2, $array1);
print_r($missing);
Copy after login

The output is as follows:

Array
(
    [1] => pear
)
Copy after login

So, in $array2, "pear" is an element that does not exist in $array1.

In addition to using the array_diff() function, you can also use a simple loop to achieve the same functionality. Loop through the second array and check if each of its elements is present in the first array. If it doesn't appear, add it to a new array.

For example, here is a sample code that achieves the same functionality through a loop:

$missing = array();
foreach ($array2 as $element) {
    if (!in_array($element, $array1)) {
        $missing[] = $element;
    }
}
print_r($missing);
Copy after login

The output is the same as before:

Array
(
    [0] => pear
)
Copy after login

No matter which method is used, you can easily find Remove an element that does not exist in an array. This will be useful when cleaning and validating array data.

The above is the detailed content of How to find non-existent elements in php array. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template