Skip to content
Advertisement

How can I eliminate repeated elements but leaving the last element in the array PHP

Well, I need to be able to eliminate the repeated elements but keeping the last element, that is, eliminate the previous ones and leave the last one.

This is what I have

exists: [
 0: {intervention_id: 2, exists: "yes"}
 1: {intervention_id: 2, exists: "no"}
 2: {intervention_id: 2, exists: "yes"}
 3: {intervention_id: 5, exists: "yes"}
 4: {intervention_id: 6, exists: "no"}
 5: {intervention_id: 12, exists: "yes"}
]

I have to delete the previous ones.

0: {intervention_id: 2, exists: "yes"}
1: {intervention_id: 2, exists: "no"}

and leave this

2: {intervention_id: 2, exists: "yes"}

And this is what I need

exists: [
 0: {intervention_id: 2, exists: "yes"}
 1: {intervention_id: 5, exists: "yes"}
 2: {intervention_id: 6, exists: "no"}
 3: {intervention_id: 12, exists: "yes"}
]

I need to keep the last one and delete the previous ones

Try this but delete the last one not the previous ones.

function unique_multidim_array($array, $key) {
    $temp_array = array();
    $i = 0;
    $key_array = array();
   
    foreach($array as $val) {
        if (!in_array($val[$key], $key_array)) {
            $key_array[$i] = $val[$key];
            $temp_array[$i] = $val;
        }
        $i++;
    }
    return $temp_array;
}

Advertisement

Answer

You could simply override the value of the current element using the same key. In this case, you will always get the last element for each ID

function unique_multidim_array($array, $key) {
    $uniq = [];
    foreach($array as $val) {
        $curVal = $val[$key]; // shortcut of the value
        $uniq[$curVal] = $val; // override previous value if exists
    }
    return array_values($uniq); // array_values to re-index array
}

$exists = [
    ['intervention_id' => 2, 'exists' => 'yes'],
    ['intervention_id' => 2, 'exists' => 'no'],
    ['intervention_id' => 2, 'exists' => 'yes'],
    ['intervention_id' => 5, 'exists' => 'yes'],
    ['intervention_id' => 6, 'exists' => 'no'],
    ['intervention_id' => 12, 'exists' => 'yes'],
];
$uniq = unique_multidim_array($exists, 'intervention_id');
print_r($uniq);

Output:

Array(
    [0] => Array(
            [intervention_id] => 2
            [exists] => yes
        )
    [1] => Array(
            [intervention_id] => 5
            [exists] => yes
        )
    [2] => Array(
            [intervention_id] => 6
            [exists] => no
        )
    [3] => Array(
            [intervention_id] => 12
            [exists] => yes
        )
)

live demo

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement