Home > front end >  How to remove all same values from an array in php
How to remove all same values from an array in php

Time:04-14

I have tried to remove all duplicate values from an array. With array_unique it's not possible to delete all same values.

My array is

array:5 [▼
 0 => "Sat 2"
 1 => "Sun 3"
 2 => "Mon 4"
 3 => "Tue 5"
 4 => "Mon 4"
]

So, basically, I want to remove "Mon 4".

So, the array should look like below:

0 => "Sat 2"
1 => "Sun 3"
3 => "Tue 5"

My code attempt:

$dates = array();
    $current = strtotime($first);
    $last = strtotime($last);

    while( $current <= $last ) {

        //if (date("D", $current) != date('D', strtotime($company_settings->holidays)))

        $dates[] = date($output_format, $current);
        $current = strtotime($step, $current);
    }

    foreach ($arr_holidays as $holi) {
        array_push($dates, $holi);
    }

    $result = array();
    foreach ($dates as $key => $value){
        if(!in_array($value, $result))
            $result[$key]=$value;
    }
    
    dd($dates);

Do you have any solution regarding this?

Thanks in advance.

CodePudding user response:

I am assuming that array contains all string data,so you can do it like below:

$valuesCounterArr = array_count_values($array);
$finalArr = [];
foreach($valuesCounterArr as $key=>$val){
    if($val == 1){
        $finalArr[] = $key;
    }
}

print_r($finalArr);

https://3v4l.org/1lc6R

CodePudding user response:

Removing all values from the array that exist more than once is equivalent to keeping all values that only exist once. This condition can be defined with a function which can easily be modified for other tasks.

$condition = function($count){
  return $count == 1;
};

Now we determine the number of values with array_count_values and filter them with our condition. The keys are then our desired result.

$result = array_keys(array_filter(array_count_values($arr),$condition));

Example with an extended array for testing yourself on https://3v4l.org/0KEdZ

CodePudding user response:

You can use the combination of array_diff, array_diff_assoc and array_unique and avoid loops for better performance.

$arr = [
    0 => "Sat 2",
    1 => "Sun 3",
    2 => "Mon 4",
    3 => "Tue 5",
    4 => "Mon 4",
   ];
$arr = array_diff($arr, array_diff_assoc($arr, array_unique($arr)));
print_r($arr);

So your output will be like this :

[0] => Sat 2 
[1] => Sun 3 
[3] => Tue 5 

https://3v4l.org/3K8ue

  •  Tags:  
  • php
  • Related