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

How to find non-existent elements in php array

PHPz
PHPzOriginal
2023-04-19 14:12:48584browse

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');

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

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

In this case, The following elements should be found:

pear

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);

The output is as follows:

Array
(
    [1] => pear
)

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);

The output is the same as before:

Array
(
    [0] => pear
)

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!

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