I have two arrays:
array('1','2','3','4');
array('4','5','6','7');
Based on them, I'd like to generate an array that contains only unique values:
array('1','2','3','4','5','6','7');
Is there any suitable function for this in PHP?
To prevent adding duplicates to an array:Use the indexOf() method to check that the value is not present in the array. The indexOf method returns -1 if the value is not contained in the array. If the condition is met, push the value to the array.
To merge elements from one array to another, we must first iterate(loop) through all the array elements. In the loop, we will retrieve each element from an array and insert(using the array push() method) to another array. Now, we can call the merge() function and pass two arrays as the arguments for merging.
In order to merge two arrays, we find its length and stored in fal and sal variable respectively. After that, we create a new integer array result which stores the sum of length of both arrays. Now, copy each elements of both arrays to the result array by using arraycopy() function.
You can use array_merge
for this and then array_unique
to remove duplicate entries.
$a = array('1','2','3','4');
$b = array('4','5','6','7');
$c = array_merge($a,$b);
var_dump(array_unique($c));
Will result in this:
array(7) {
[0]=>
string(1) "1"
[1]=>
string(1) "2"
[2]=>
string(1) "3"
[3]=>
string(1) "4"
[5]=>
string(1) "5"
[6]=>
string(1) "6"
[7]=>
string(1) "7"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With