How to remove certain keys from an array in php

For example there is such an array:

Array
(
    [ID] => 4
    [DATE_CREATE] => 04.10.2013 20:47:52
    [NAME] => BCAA
    [DEPTH_LEVEL] => 1
    [DESCRIPTION] => 
    [SEARCHABLE_CONTENT] => BCAA
    [CODE] => bcaa
    [DETAIL_PICTURE] =>
)

How to remove certain keys from an array so that the result is the following:

Array
(
    [ID] => 4
    [DATE_CREATE] => 04.10.2013 20:47:52
    [NAME] => BCAA
    [DEPTH_LEVEL] => 1
)

Thank you in advance!

Author: bruiser, 2013-12-29

4 answers

$arr = array('id' => 4, 'date_create' => '4.10.2013 20:47:52', 'name' => 'BCAA', 'depth_level' => 1, 'description' => null, 'searchable_content' => 'BCAA', 'code' => 'BCAA', 'detail_picture' => null);
$delete_keys = array('description', 'searchable_content', 'code', 'detail_picture');

$arr = array_diff_key($arr, array_flip($delete_keys)); // Only one line!
 2
Author: Slava Konashkov, 2014-02-18 10:12:31

You can create an array with the keys to be removed from the original array and loop through to check whether the current key matches the key to be removed. If not, write the value to a new array:

$arr = array('id' => 4, 'date_create' => '4.10.2013 20:47:52', 'name' => 'BCAA', 'depth_level' => 1, 'description' => null, 'searchable_content' => 'BCAA', 'code' => 'BCAA', 'detail_picture' => null);
$delete_keys = array('description', 'searchable_content', 'code', 'detail_picture');
$new_arr = array();
foreach ($arr as $key => $value) {
    if (!in_array($key, $delete_keys)) {
        $new_arr[$key] = $value;
    }
}

Option with changing the current array:

$arr = array('id' => 4, 'date_create' => '4.10.2013 20:47:52', 'name' => 'BCAA', 'depth_level' => 1, 'description' => null, 'searchable_content' => 'BCAA', 'code' => 'BCAA', 'detail_picture' => null);
$delete_keys = array('description', 'searchable_content', 'code', 'detail_picture');
foreach ($arr as $key => $value) {
    if (in_array($key, $delete_keys)) {
        unset($arr[$key]);
    }
}
 1
Author: andreyqin, 2013-12-29 10:35:27
$old_array = array('ID' => '4', 'DATE_CREATE' => '04.10.2013 20:47:52', 'NAME' => 'BCAA', 'DEPTH_LEVEL' => '1', 'DESCRIPTION' => '', 'SEARCHABLE_CONTENT' => 'BCAA', 'CODE' => 'bcaa', 'DETAIL_PICTURE' => '');

$new_array = array('ID' => '', 'DATE_CREATE' => '', 'NAME' => '', 'DEPTH_LEVEL' => '');

$new_array = array_intersect_key($old_array, $new_array);

The fastest option from the point of view of performance of all the proposed ones. But there are also disadvantages.

 1
Author: Равнодушный, 2014-02-18 12:29:33

$columns = array_diff_key($columns, array_flip([
    'ID',
    'DATE_CREATE',
    'NAME',
    'DEPTH_LEVEL',
]));
 0
Author: user312794, 2018-10-19 01:18:37