jmwhitaker Posted January 30, 2012 Share Posted January 30, 2012 Hello. I am editing a plugin that is grabbing a multidimensional array, then breaking it out into a foreach statement and doing stuff with the resulting data. What I am trying to do is edit the array before it gets to the foreach statement. I want to look and see if there is a key/value combination that exists, and if it does remove that entire subarray, then reform the array and pass it to a new variable. The current variable $arrSlides returns several subarrays that look like something like this (I remove unimportant variables for the sake of brevity): Array ( [0] => Array ( [slide_active] => 1 ) [1] => Array ( [slide_active] => 0 ) ) What I want to do is look and see if one of these subarrays contains the key slide_active with a value of 0. If it contains a value of zero, I want to dump the whole subarray altogether, then reform the multidimensional array back into the variable $arrSlides . I have tried a few array functions but have not had any luck. Any suggestions? Thanks in advance, Jason Quote Link to comment Share on other sites More sharing options...
Pikachu2000 Posted January 30, 2012 Share Posted January 30, 2012 Offhand, I can't think of a way to do it without looping over the array, but if the primary array indices are sequential from zero and numeric, you can use a for() loop instead of a foreach() loop. Might be a little faster. $elements = count($arrSlides); for( $i = 0; $i < $elements; $i++ ) { if( array_key_exists('slide_active', $arrSlides[$i]) ) { if( $arrSlides[$i]['slide_active'] != 1 ) { unset( $arrSlides[$i] ); } } } Quote Link to comment Share on other sites More sharing options...
Psycho Posted January 30, 2012 Share Posted January 30, 2012 I think array_filter() would be a better option for this: function removeInactiveSlides($sub) { return (!(isset($sub['slide_active']) && $sub['slide_active']===0)); } $arrSlidesFiltered = array_filter($arrSlides, 'removeInactiveSlides'); Quote Link to comment Share on other sites More sharing options...
jmwhitaker Posted January 30, 2012 Author Share Posted January 30, 2012 Thanks! I wanted to avoid rewriting the 300 line foreach statement that was outputting all the variables, so I took a bit of your solution and checked to see if the key/value combo existed, unset the value if it did, then did an else for all other instances of the foreach: foreach ($arrSlides as $i => $slide){ if ($slide['slide_active'] == 0){ unset($slide); } else { put stuff here } Thanks for pointing me in the right direction! Also, to @psycho... Your solution also worked perfectly, especially for doing the filtering prior to the foreach statement. Thanks! Jason Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.