0

I have an array below in which I want to get or remove duplicate values:

$data = $responses;
var_dump($data);

result is:

array(11) {
  [0]=>
    string(4) "date"
  [1]=>
     string(4) "name"
  [2]=>
     string(10) "start_time"
  [3]=>
     string(8) "end_time"
  [4]=>
     string(4) "date"
  [5]=>
     string(4) "name"
  [6]=>
     string(10) "start_time"
  [7]=>
     string(8) "end_time"
  [8]=>
     string(7) "other_1"
  [9]=>
     string(7) "other_2"
  [10]=>
     string(7) "other_3"
}

So I do :

var_dump(array_unique($data));
//also tried:
var_dump(array_intersect_key($data, array_unique(array_map('serialize', $data))));

but the output is:

array(6) {
  [0]=>
    string(4) "date"
  [1]=>
     string(4) "name"
  [2]=>
     string(10) "start_time"
  [3]=>
     string(8) "end_time"
  [4]=>
     string(7) "other_1"
  [5]=>
     string(7) "other_2"
  [6]=>
     string(7) "other_3"
}

The output I am expecting is:

array(3){
  [1]=>
     string(7) "other_1"
  [2]=>
     string(7) "other_2"
  [3]=>
     string(7) "other_3"
}

I am expecting to have the last 3 items to be returned only for they are the only values that are not duplicate, but I think array_unique is just retaining one single value of the duplicate items. Am I doing array_unique the right way?

Eem Jee
  • 1,239
  • 5
  • 30
  • 64
  • @mickmackusa thanks for the redirection, but the output is like this : `array ( 0 => 'other_1', 1 => 'other_2', 2 => 'other_3', )NULL` . can we remove NULL? – Eem Jee Dec 14 '18 at 03:43
  • If you need the keys to start from `1`, then use `array_unshift()` a dummy value to the array, then `unset()` it. If my other answer helped you, you may upvote it. – mickmackusa Dec 14 '18 at 03:45
  • @mickmackusa I mean the `NULL` after the parenthesis. – Eem Jee Dec 14 '18 at 03:46
  • @mickmackusa I have just copied the code from your answer on that link :) – Eem Jee Dec 14 '18 at 03:49
  • I am suggesting that it is something else in your code that is generating NULL (beyond my snippet). – mickmackusa Dec 14 '18 at 03:49
  • https://3v4l.org/eYIia – mickmackusa Dec 14 '18 at 03:51
  • @mickmackusa Okay. I have sorted it out. Can we store this one to an array? I have tried typecasting it, but doesn't work. – Eem Jee Dec 14 '18 at 03:59
  • I don't understand your question extension. You can show me in a 3v4l link and I can review your attempt if you like. Are you asking how to push it into another array? You may accept the duplicate that I have provided. – mickmackusa Dec 14 '18 at 03:59
  • @mickmackusa Yes, I want them to be an array, or create the result to an array. – Eem Jee Dec 14 '18 at 05:19
  • The result is an array (with 3 elements in it). You'll need to better describe what you desire. – mickmackusa Dec 14 '18 at 05:24
  • 1
    @mickmackusa just got it (phew) just removed `var_export` – Eem Jee Dec 14 '18 at 05:30

0 Answers0