0

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

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

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

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

How can I get the missing values of $sample_data in $headings array & get output for this example like this- $result=['email', 'meta_data']

Thanks in advance.

1
  • 1
    What have you tried so far? Where are you stuck? Why is this tagged with Laravel without sharing any related code? Commented Mar 8, 2022 at 8:38

2 Answers 2

1

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
)
Sign up to request clarification or add additional context in comments.

1 Comment

I like this better. As it uses core PHP.
0

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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.