1

I am attempting to use array_diff to exclude certain elements from an array. According to the docs: "Returns an array containing all the entries from array1 that are not present in any of the other arrays."

In my code below I have an array which represents the data return from the database when requesting a user. I have another array which contains the elements I don't want to be included in the array. Here is the code ...

$user = array(
    'id' => '9',
    'password' => 'CRYPT_BLOWFISH HASH',
    'username' => 'Billy',
    'phone' => '+447777777777');

$columnsToExclude = array('password', 'phone');

var_dump(array_diff($user, $columnsToExclude));

I'm not understanding what I'm doing wrong, unless I can't use a sequential array as the second argument.

What am I doing wrong?

Edit:

As suggested in comments, I have tried array_diff_key and I get the same results.

array_diff_key($user, $columnsToExclude));
2

1 Answer 1

2

array_diff returns all your values from $user which do not have matching values in $columnsToExclude. The values in $columnsToExclude are "password" and "phone". None of these values exist in $user. The result is expected. You want to do this diff on the keys, and you also need to make "password" and "phone" keys in the array, not values:

array_diff_key($users, array_flip($columnsToExclude))
Sign up to request clarification or add additional context in comments.

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.