1

I have two arrays:

$array = new Array('id'=>1, 'name'=>'Peter', 'sex'=>'male', 'age'=>25);

$excludes = new Array('sex', 'age');

I want to get the following result:

$array = new Array('id'=>1, 'name'=>'Peter');

The items whose keys are found in the array $excludes are removed.

How can I achieve this conveniently?

2
  • 2
    For loop and unset by the keys ? Commented Aug 15, 2017 at 6:47
  • Thank you! But I want a more convenient method. In fact, there has been one, contributed by @RomanPerekhrest. You can see his answer. Commented Aug 15, 2017 at 7:12

2 Answers 2

4

Simply with array_diff_key and array_flip functions:

// $arr is your initial array (besides, don't give `$array` name to arrays)
$result = array_diff_key($arr, array_flip($excludes));
print_r($result);

The output:

Array
(
    [id] => 1
    [name] => Peter
)
Sign up to request clarification or add additional context in comments.

3 Comments

Wow! That's cool! That's what I want! Thank you so much! I'm excited to get this wonderful answer so soon! Really really thank you!
@RomanPerekhrest I have a question is this way is more efficient then just make for loop ?
@Avihaym, for such "small" input arrays - the difference won't be essential and critical. We may start benchmarking when dealing with big arrays (thousands/millions items)
1
function removeExcludesFromArray($input,$expludes) {
    $newArray = array(); // Create a new empty array
    foreach($array as $inputKey => $inputElement) { // loop your original array
        if(!array_key_exists($inputKey,$excludes)) { // check if key exists
             $newArray[$inputKey] = $inputElement; // add on demand
         }
     }

     return $newArray; // return the result
}


// Call the function
$array = removeExcludesFromArray($array,$excludes);

2 Comments

It's always better to use functionality already provided by PHP itself, see the other answer.
Thank you! But I want a more convenient method. In fact, there has been one, contributed by @RomanPerekhrest. You can see his answer. Anyway, thank you very much for your help!

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.