Reputation: 9221
I have a foreach iterator, there are 500 group items
in it. How do I remove duplicate values in a foreach?
foreach ($data as $data) {
if(!empty($data['name'])){ //check if have $data['name']
$name = $data['name'];
$id = $data['id'];
$date = $data['date'];
$link = $data['link'];
if(strpos($link, '.ads.')){
continue; //remove all the link contains `.ads.`
}else{
// if `$link` is not repeat, echo the below data. how to use array_unique, remove all the values which repear in `$link` part?
echo $name;
echo $id;
echo $date;
echo $link;
}
}
Upvotes: 2
Views: 25401
Reputation: 11
$fetch=$q->result();
$array_result= json_decode(json_encode($fetch), true);
$g=array();
foreach($array_result as $p)
{
array_push($g,$p['email']);
}
$array=array_values(array_filter(array_unique($g)));
I was using this when i had o choose unique e-mail id's out of a number of similar emails which was coming via Ajax response...hope this helps u can ask queries if u do hv problem understanding anywhere..
Upvotes: 1
Reputation: 197732
Look what you do:
foreach ($data as $data)
You are overwriting the contents of $data
, then you access $data
while you expect it still to be the original array. That's just wrong.
Take an additional variable name, pretty common is $value
:
foreach ($data as $value)
Hope this helps even if it is not answering your question, but this can be part of your problem, so take care ;)
Upvotes: 3
Reputation: 287835
With array_unique
:
foreach (array_unique($data) as $d) {
// Do stuff with $d ...
}
Although you can technically call the array and its elements by the same name, it's bound to lead to programming errors and confusion afterwards.
Upvotes: 15