Guidelines

This site is for tech Q&A. Please keep your posts focused on the subject at hand.

Ask one question at a time. Don't conflate multiple problems into a single question.

Make sure to include all relevant information in your posts. Try to avoid linking to external sites.

Links to documentation are fine, but in addition you should also quote the relevant parts in your posts.

1 vote
884 views
884 views

I would like to remove, delete, unset, or filter out the all array elements if they are matched with a condition.

$array = array("Blue Jeans", "Red Pajamas", "Kleenex Used By Dr. Dre");

The two separate conditions are:

  1. If the length of elements is less than 15 bytes (or 15 characters). Like in the above example, the first two elements should be crossed out.
  2. If an element contains the word "Red" (or the string "Red") which is not case-sensitive, it will be deleted. Like in the the above example, the second key should be deleted.

How should I do to check and process the two conditions separately, or more ideally, in one step?

in Scripting
by (50)
1 4
edit history

Please log in or register to answer this question.

1 Answer

1 vote
 

To filter an array for particular elements use the array_filter() function. The function takes 2 arguments: an array and a callback function¹. The callback function is applied to all array elements and only those elements for which the callback function evaluates to true are returned. You can use either a named function

function myfilter($v) {
  return !((strlen($v) < 15) || (strpos($v, 'red') !== false));
}

$result = array_filter($array, 'myfilter');

or an anonymous function (AKA lambda expression)

$callback = function($v) {
  return !((strlen($v) < 15) || (strpos($v, 'red') !== false));
}

$result = array_filter($array, $callback);

Both approaches will return the result

Array
(
    [2] => Kleenex Used By Dr. Dre
)

Use the function array_values() on the result if you want a new zero-based array instead of an array where the keys are the indexes from the original array:

$result = array_values(array_filter($array, $callback));

Result:

Array
(
    [0] => Kleenex Used By Dr. Dre
)

¹ Actually, array_filter() takes 3 arguments: array, callback function, and mode. The third parameter (mode) is optional and controls whether the callback function is applied to values and/or keys of the array. The default is to apply it to values only, which is what you want in your scenario, hence you need to provide only the first 2 parameters.

by (100)
1 13 28
edit history
 
Thank you.  Happy New Year!
 
You're welcome, and Happy New Year to you too.
...