Home > Mobile >  Check and return missing values from an array
Check and return missing values from an array

Time:03-08

I am working in a laravel project. I've an array named $headings like this-

  0 => array:1 [
    0 => array:4 [
      0 => "name"
      1 => "phone_number"
      2 => "department"
      3 => "division"
      4 => "status"
    ]
  ]
]

And I've another sample array named $sample_data like this-

array:2 [
  0 => "name"
  1 => "email"
  2 => "meta_data"
]

How can I get the missing values of $sample_data in $headings array- Thanks in advance.

CodePudding user response:

Use array_diff()

$headings = [
    0 => "name",
    1 => "phone_number",
    2 => "department",
    3 => "division",
    4 => "status"
];

$sample_data = [
  0 => "name",
  1 => "email",
  2 => "meta_data"
];

$difference = array_diff($headings, $sample_data);
print_r($difference);

Output:


Array
(
    [1] => phone_number
    [2] => department
    [3] => division
    [4] => status
)

CodePudding user response:

Use Laravel Collections, with the diff() method, that compares arrays. You have to wrap everything in Collections, to achieve this. You can find the diff() documentation here.

$headings = collect($headings[0]); // unpack it from the first array it is wrapped in
$sampleData = collect($sampleData);

$diff = $headings->diff($sampleData);

// should be ['phone_number', 'department', 'division', 'status']
$diff->all();
  • Related