2

How to unset() some parts of my multimensional array?

I have an array similar like

$list['A_1']['AA_2']['AAA_3']['AAAA_4'] = 'stuff'; 
$list['B_1']['BB_2']['BBB_3'] = 'stuff'; 
$list['C_1']['CC_2']['CCC_3']['CCCC_4']['CCCCC_5']['CCCCCC_6']['CCCCCCC_7']['CCCCCCCC_8'] = 'stuff'; 
$list['D_1']['DD_2']['DDD_3']['DDDD_4']['DDDDD_5'] = 'stuff'; 

Normally I would do my desired unset()-ing with

unset( $list['A_1']['AA_2']['AAA_3'] );
unset( $list['B_1']['BB_2']['BBB_3'] );
unset( $list['C_1']['CC_2']['CCC_3']['CCCC_4']['CCCCC_5'] );
unset( $list['D_1']['DD_2']['DDD_3']['DDDD_4'] ); 

However I'd like to get the same result by unsetting them using the elements from another array:

$result = array('A_1','AA_2','AAA_3');
$result = array('B_1','BB_2','BBB_3');
$result = array('C_1','CC_2','CCC_3','CCCC_4','CCCCC_5');
$result = array('D_1','DD_2','DDD_3','DDDD_4');

I've tried to approach it with the simplest way I could imagine but sadly it's not as easy as that and doesn't work:

$result = array('A_1','AA_2','AAA_3');    
unset( $list[$result] ); 

returns: Warning: Illegal offset type in unset

2 Answers 2

1

This should be worked

function unsetArray(&$list, $result) {
    eval("unset("."\$list['".implode("']['", $result)."']".");");
}
unsetArray($list, $result);
var_dump($list);
Sign up to request clarification or add additional context in comments.

1 Comment

TBH I was hoping for something more sophisticated (read: non-eval) but it does do the job. Thanks for that! Small note for others though, don't forget to sanitize the elements of $list or Eval can become Evil in a snap of a finger.
0

You need to form multidemensional array to unset. Here you are using single dimensional array. Just form array inside array in your result array.

Thanks.

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.