Search code examples
phparraysunsetarray-unset

Efficient way to remove key-value from Array of Arrays


I have an array of 50000 arrays and i want to remove the "id" key-value pair from each of them.

I would rather not loop through 50k elements and was wondering if there was an efficient way to do it.

Array
(
    [0] => Array
        (
            [id] => 713061
            [market] => usd-btc
            [price] => 3893.69
        )

    [1] => Array
        (
            [id] => 713056
            [market] => usd-btc
            [price] => 3893.69
        )

    [2] => Array
        (
            [id] => 713051
            [market] => usd-btc
            [price] => 3893.69
        )

    [3] => Array
        (
            [id] => 713046
            [market] => usd-btc
            [price] => 3893.69
        )

    [4] => Array
        (
            [id] => 713041
            [market] => usd-btc
            [price] => 3892.95
        )

    [5] => Array
        (
            [id] => 713036
            [market] => usd-btc
            [price] => 3892.95
        )

I tried both the following but does not seem to be working:

// Remove ID
        foreach($server_data as $sd)
        {
            unset($sd['id']);
        }

        unset($server_data['id']);

        PRINT_R($server_data);

The $server_data is still returning the array with the $id element;

Any thoughts?


Solution

  • This creates a copy of the subarray, so when you change it, the main array is not affected:

    foreach ($server_data as $sd)
    {
        unset($sd['id']);
    }
    

    You can unset from the original array:

    foreach (array_keys($server_data) as $index)
    {
        unset($server_data[$index]['id']);
    }
    

    Or pass the subarray a reference so that the original is changed:

    foreach ($server_data as &$sd)
    {
        unset($sd['id']);
    }
    

    Or, more tersely:

    array_walk($server_data, function (&$item) { unset($item['id']); });