Hans Pede Hans Pede - 5 months ago 10
PHP Question

Removing row from array, if value exist

imagine I got the following array:


Array (

[0] => Array ( [id] => 1 [code] => '342')

[1] => Array ( [id] => 2 [code] => '765')

[2] => Array ( [id] => 3 [code] => '134')

[3] => Array ( [id] => 1 [code] => '999'))


Here Array[0]['id'] and Array[3]['id'] is a duplicate with respect to ['id']. I want to remove one of them (doesn't matter which). Actually I thought I found a solution with this code:

//data
$row = $stmt->fetchALL(PDO::FETCH_ASSOC);

$ids = array();
for($i = 0;$i < count($row); $i++ )
{
if (in_array($row[$i]['id'], $ids))
{
unset($row[$i]);
continue;
}

$ids[] = $row[$i]['id'];

}

print_r($row);


For some reason it works well with small arrays, but if I have a lot of values in it with multiple dublicates, it fails. Any suggest what I am missing ?

Answer

Simple solution using regular foreach loop:

$rows = [
    ['id' => 1, 'code' => '342'],
    ['id' => 2, 'code' => '765'],
    ['id' => 3, 'code' => '134'],
    ['id' => 1, 'code' => '342']
];

$ids = [];
foreach ($rows as $k => $item) {
    if (in_array($item['id'], $ids)){
         unset($rows[$k]);            
    } else {
         $ids[] = $item['id'];
    }    
}

print_r($rows);