Verification of repeated information in array

Asked

Viewed 48 times

0

I have two arrays as I would do in PHP to return in a third array only numbers that are not in the first and second array.

Example:

If I have the number 1 and 2 in the first array my third array should receive only 3 and 4

$primeiro_array = ["1", "2", "3", "4"];
$segundo_array = ["1", "2"];

That third array will only receive numbers that are not repeated between the first and second array

$terceiro_array = ["3", "4"];

There is a way to do this with PHP?

  • 1

    "only numbers that are not in the first and second array" this got quite confusing.

3 answers

5


array_diff

(PHP 4 >= 4.0.1, PHP 5, PHP 7)

array_diff - Computes the differences between arrays

array_diff ( array $array1 , array $array2 [, array $ ... ] ) : array

Compares array1 with one or more arrays and returns the values in array1 that are not present in any of the other arrays.

Example:

$array1 = ['1', '2', '3', '4'];
$array2 = ['1', '2'];

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

print_r($array3);

Exit

Array
(
    [2] => 3
    [3] => 4
)

3

Use the function array_diff

$primeiro_array = ["1", "2", "3", "4"];
$segundo_array = ["1", "2"];

$terceiro_array = array_diff($primeiro_array, $segundo_array);

this way it will bring the expected result, but, with the current indexing, to improve this can make a array_values:

$terceiro_array = array_values(array_diff($primeiro_array, $segundo_array));

to match the question.

Result Online Example

References:

-4

There is a function called "in_array" where it returns if 'x' value is present in the array in question. With a foreach/if/Else structure you would get this result you want to check your numbers in the array http://php.net/manual/fr/function.in-array.php

Browser other questions tagged

You are not signed in. Login or sign up in order to post.