Ari Takeshi
Ari Takeshi

Reputation: 934

Unset variable specific key from multidimensional array

I have different multidimensional arrays with different keys and values:

$array_1 = array('cars' => array('audi' => array('a3' => array('one', 'two', 'three'), 'a5' => array('five', 'six', 'seven')), 'mercedes' => array('type_1' => array('submodel' => array('whatever'))), 'other_cat' => array('different_things')));

then I would like to unset a specific key, for example:

unset($array_1['cars']['audi']['a5']);

Now I like to "split it up", to have the key variable.

$to_unset = ['cars']['audi']['a5']; 

How can I unset that specific (variable!) key?

Aäron

Upvotes: 0

Views: 295

Answers (3)

Jesse Schokker
Jesse Schokker

Reputation: 896

An easy utility to avoid removing array keys that do not exist by accident:

function removeArrayKey($path, &$array ) {

    $array_temp = &$array;
    $previousItem = null;

    $path_bits = explode( ".", $path );

        foreach( $path_bits as &$path_bit ) {

           if( !isset( $array_temp[ $path_bit ] ) ) {
                  die("Error" . $path_bit);
                   //throw new Exception( "Path does not exist in array" );
            }

            $previousItem = &$array_temp;
            $array_temp = &$array_temp[ $path_bit ];

        }

        if( isset( $previousItem ) ) {

             unset( $previousItem[ $path_bit ] );

        }

        return $array;

}

To use the function, simply use removeArrayKey( "cars.mercedes.cars", $array_1 ); and separate each array index with a .

Upvotes: 1

Chin Leung
Chin Leung

Reputation: 14921

You can probably go with eval but it's not recommended.

eval('unset($array_1' . $to_unset . ');');

Upvotes: 0

Björn Pfoster
Björn Pfoster

Reputation: 125

So as i see your problem, you'd like to save your array path into a variable. You can solve this problem on two different ways:

Save every key into a variable

The way i would do it, if my array structure looks always the same (e.g. [cars][type][model]). You can save the key to delete into a variable:

$cars = 'cars';
$type = 'audi';
$model = 'a5';

unset($array_1[$cars][$type][$model]);

This will work excellent in a for(each) loop.

Saving your keys into an array

This method will save your problem, but it is not the best option. You can save all the keys you like to unset into an array. This way can cause many bugs and you should reconsider your array structure, if this way is your solution.

// arrays start at 0
$to_unset = [
    0 => 'cars',
    1 => 'audi',
    2 => 'a5',
];

unset($array_1[$to_unset[0]][$to_unset[1]][$to_unset[2]]);

An other possible option here is to name the keys of the $to_unset array.

// arrays start at 0
$to_unset = [
    'cars' => 'cars',
    'type' => 'audi',
    'model' => 'a5',
];

unset($array_1[$to_unset['cars']][$to_unset['type']][$to_unset['model']]);

Upvotes: 0

Related Questions