I was enlightened the day I discovered
array_filter. You may find yourself with an array of values and you want to delete some of those values from the array. There is no ‘delete element from array’ function built into php but you can use an even more powerful function,
Let’s look at a simple example. I have an array containing values, some are numeric, some might not be. I only want my array to contain the valid numeric entries and I want to delete the other values. PHP has a helper function we are going to be utilizing,
- $data = array(42, "foo", 96, "", 100.96, "php");
- // Filter each value of $data through the function is_numeric
- $numeric_data = array_filter($data, "is_numeric");
- // Re-key the array so the keys are sequential and numeric (starting at 0)
- $numeric_data = array_values($numeric_data);
- // Print out the new, filtered data
The output from above is:
Array (  => 42  => 96  => 100.96 )
Pretty handy function. Notice how I ran my data through the function
array_values, before that function was run, the keys were
Another example with a user defined function. I have defined a collection of tags and I want my tag collection to only contain tags that match the criteria the user has requested.
- // Custom function used to filter the $tagCollection based on query sent to page
- function strTagMatch($val)
- $query = isset($_REQUEST['Tags']) ? $_REQUEST['Tags'] : '';
- return (stripos($val, $query) !== false);
- $tags = array_filter($tagCollection, "strTagMatch");
Voila! Deleting elements from an array has never been easier.
For more information, see the php documentation on array_filter.