Remove element from multidimensional array php
I'm trying to delete elements from a multidimensional-array based on a value. In this case if a sub-array's key 'year' has the value 2011 I want that sub-array out. Just for the record: i'm running PHP 5.2. My array looks like this:
BoltClock 674k155 gold badges1361 silver badges1333 bronze badges asked Dec 16, 2010 at 22:52
Try this:
Then you would call it like this:
answered Dec 16, 2010 at 23:40
driangledriangle 11.5k4 gold badges45 silver badges51 bronze badges 3 Try this:
answered Dec 16, 2010 at 22:54
Jacob RelkinJacob Relkin 158k32 gold badges341 silver badges318 bronze badges 2
answered Dec 17, 2010 at 0:08
ifaourifaour 37.9k12 gold badges71 silver badges79 bronze badges 0 For a single, known value, put this in beginning of iteration through the multidimensional array:
Simply skips that entire iteration if your criteria are true. Alternately you could do the reverse. Might be easier to read, depending on taste:
I dunno. Maybe this looks hacky to some. I like it, though. Short, quick and simple. Looked like the purpose of filtering in this case was to print out some contents and skip some, based on certain criteria. If you do the filtering before the loop, you'll have to loop through the entire thing twice - once to filter and once to print the contents. If you do it like this, inside the loop, that is not required. You also won't alter your array except for inside of the loop, which can be helpful if you don't always want to filter by these criteria in particular. answered Sep 18, 2013 at 9:02
answered Aug 31, 2018 at 4:39
Here is my approach to this problem: use
And even simpler with the anonymous functions of PHP > 5.3
* Note the use of loose comparison, hence it works with integers too. answered Jan 8, 2020 at 10:00
nobugnobug 1521 silver badge7 bronze badges This is how I achieved it:
Note: How is my answer different than answer sent by driangle? As the answer by NiDBiLD and Abdulrazzak Jakati, the solution is quite similar to the one chosen by the asker by best answer. However, there are differences in the customized implementations that can be useful for readers to fully understand solution. My solution was applied to a real project and it is guaranteed to work properly. It is not only a prototype, but something that works correctly for sure. Please also review NiDBiLD and Abdulrazzak Jakati solutions that are quite similar to the one in the best answer and still add value to readers. answered Feb 11 at 18:01
Jaime MontoyaJaime Montoya 6,1667 gold badges61 silver badges87 bronze badges Not the answer you're looking for? Browse other questions tagged php arrays multidimensional-array or ask your own question. |