0

My first array is like:

Array ( [0] => Array ( [column_name] => ben_firstname ) ) 

Second array:

Array ( [0] => Array ( [column_name] => ben_unique_id )
        [1] => Array ( [column_name] => ben_firstname )
        [2] => Array ( [column_name] => ben_lastname )
        [3] => Array ( [column_name] => ben_middlename ) )

I want to remove ben_firstname (which is in first array) from second array...

I tried with array_diff function. But, I am getting error.

CODE:

print_r(array_diff($first_array, $second_array));

ERROR:

 Message: Array to string conversion

Thanks for your help.

2
  • 3
    What error? Show some code please. Commented Jun 3, 2014 at 21:46
  • "I tried with array_diff function." - Show your approach. "But, I am getting error." - What error? Post the output. Commented Jun 3, 2014 at 21:47

2 Answers 2

5

You can't use array_diff directly because that function expects array elements to be scalar, while in your case they are themselves arrays.

The correct solution is to use array_udiff with a callback that determines equality by looking at the column_name key of each array:

$result = array_udiff(
     $second,
     $first, 
     function($x, $y) { return strcmp($x['column_name'], $y['column_name']); }
);

See it in action.

Sign up to request clarification or add additional context in comments.

Comments

0

You need to do:

$newArray = array_diff($array2, $array1);

The order is important. What error are you getting?

EDIT: Your error is that you're trying to print an array, not that the array_diff didn't work.

If you want to print a PHP array, print_r should work. What PHP version are you on?

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.