StringerB
StringerB

Reputation: 75

php - remove indexes of an aray if they have the same value

How can i make the values of such an array unique.

Array ( [0] => Array ( [0] => wallet [1] => pen [2] => perfume [3] => pen) )

as there is pen twice i would like it to be deleted in this way :

( [0] => Array ( [0] => wallet [1] => pen [2] => perfume) )

OR

( [0] => Array ( [0] => wallet [1] => perfume [2] => pen) )

and i would like it to apply for any length.

thanks for your help

Upvotes: 0

Views: 193

Answers (4)

Toto
Toto

Reputation: 91385

How about array_flip used twice:

$arr = Array(0 => wallet, 1 => pen, 2 => perfume, 3 => pen);
$arr = array_flip(array_flip($arr));
print_r($arr);

output:

Array
(
    [0] => wallet
    [3] => pen
    [2] => perfume
)

If you want to renumbered the indexes, add this ligne after:

$arr = array_values($arr);

Upvotes: 2

Prasanth Bendra
Prasanth Bendra

Reputation: 32740

Here is the solution for multi dimensopnal array

$res  = array();
foreach($your_array as $key=>$val){
  $res[$key] = array_unique($val);
}

echo "<pre>";
print_r($res);

Upvotes: 0

Othman
Othman

Reputation: 3018

if you just want to select a unique value you need to pass the array that you want to compare the values, I am assuming you passed the main array, you need to pass the array where the problem is found which is in your case the index 0 of an array

$result = array_unique($input[0]);

$input will have an array of unique values so pen will not be 2

if you need to delete any duplicated values in the array you can do this.

$input[0] = array_unique($input[0]);

if you need to reset the index you can use this

$new_index = array_values($input[0]);
print_r($new_index);

Upvotes: 1

Vivek Goel
Vivek Goel

Reputation: 24140

$tmp = array ();

foreach ($array as $row) 
             array_push($tmp,array_unique($row));

Upvotes: 0

Related Questions