arrays - How to find duplicate value on foreach php
i'm stuck there, i want to check and find duplicate data with value[session_id] and value[customer_id]
My array like this:
$data = [
[
'session_id' => 'abcd',
'customer_id' => '123',
'val' => 'abcd123',
],
[
'session_id' => 'xyz',
'customer_id' => '123',
'val' => 'abcd123',
],
[
'session_id' => 'abcdefgh',
'customer_id' => '123',
'val' => 'abcd123',
],
[
'session_id' => 'abcd',
'customer_id' => '123',
'val' => 'abcd123',
],
[
'session_id' => 'abcdefgh',
'customer_id' => '123',
'val' => 'abcd123',
],
[
'session_id' => 'abcd',
'customer_id' => '1234',
'val' => 'abcd123',
],
];
How to use foreach and get new array checked duplicate, i want get new array like this.
$newArray = [
[
'session_id' => 'abcd',
'customer_id' => '123',
'val' => 'abcd123',
],
[
'session_id' => 'xyz',
'customer_id' => '123',
'val' => 'abcd123',
],
[
'session_id' => 'abcdefgh',
'customer_id' => '123',
'val' => 'abcd123',
],
[
'session_id' => 'abcd',
'customer_id' => '1234',
'val' => 'abcd123',
],
];
Thanks all, happy coding <3
Answer
Solution:
I think this will be helpful for you.
$newArray=array();
foreach ($data as $value) {
$found=0;//If no duplicate found then it will be zero
foreach ($newArray as $v) {
if(($v['session_id']==$value['session_id'] && $v['customer_id']==$value['customer_id'])){
// Duplicate Exist
$found=1;
break;
}
}
if(!$found){//No duplicate found in $newArray
$newArray[]=$value;
}
}
print_r($newArray);
Output:
Array
(
[0] => Array
(
[session_id] => abcd
[customer_id] => 123
[val] => abcd123
)
[1] => Array
(
[session_id] => xyz
[customer_id] => 123
[val] => abcd123
)
[2] => Array
(
[session_id] => abcdefgh
[customer_id] => 123
[val] => abcd123
)
[3] => Array
(
[session_id] => abcd
[customer_id] => 1234
[val] => abcd123
)
)
Source