abhit
abhit

Reputation: 981

remove one array index if other has the same value?

I have an array as:

$check = [
   0 => [
     'id' => '1',
     'value' => 'true'
   ]

   1 => [
     'id' => '1',
     'value' => 'false'
   ]

   2 => [
     'id' => '1',
     'value' => 'true'
   ]

   3 => [
     'id' => '2',
     'value' => 'true'
   ]
]

Now I want to convert this array into

$check = [
   0 => [
     'id' => '1',
     'value' => 'true'
   ]

   1 => [
      'id' => '2',
      'value' => 'true'
   ]
]

i.e if the indexes of my check[] has same id value then delete all of them except for any one.

Upvotes: 0

Views: 199

Answers (1)

Tahir Raza
Tahir Raza

Reputation: 736

Firstly, you have a syntax error in your array. Missing , in between arrays and I have corrected your array. See the code below.

The php function you're looking for is array_unique().

Pass SORT_REGULAR flag as function's second parameter, it means compare items normally (don't change types)

Check your validated code here.

NOTE: Don't forget to select Php compiler from the dropdown.

<?php

$check = [
   0 => [
     'id' => '1',
     'value' => 'true'
   ],

   1 => [
     'id' => '1',
     'value' => 'true'
   ],

   2 => [
     'id' => '1',
     'value' => 'true'
   ],

   3 => [
     'id' => '2',
     'value' => 'true'
   ]
];
print_r(array_unique($check, SORT_REGULAR));

Upvotes: 1

Related Questions