You are viewing an older version of the site. Click here to view
the latest version of this page. (This may be a dead link, if so, try the root page of the docs
here.)
== array_filter ==
Copy Code
The output would be:
Copy Code
The output would be:
Filters an array by callback. The items in the array are iterated over, each one sent to the closure one at a time, as key, value. The closure should return true if the item should be included in the array, or false if not. The filtered array is then returned by the function. If the array is associative, the keys will continue to map to the same values, however a normal array, the values are simply pushed onto the new array, and won't correspond to the same values per se.
=== Vital Info ===
{| style="width: 40%;" cellspacing="1" cellpadding="1" border="1" class="wikitable"
|-
! scope="col" width="20%" |
! scope="col" width="80%" |
|-
! scope="row" | Name
| array_filter
|-
! scope="row" | Returns
| array
|-
! scope="row" | Usages
| array, boolean closure(key, value)
|-
! scope="row" | Throws
| [[../objects/ms.lang.CastException|ms.lang.CastException]]
|-
! scope="row" | Since
| 3.3.1
|-
! scope="row" | Restricted
| No
|-
! scope="row" | Optimizations
| None
|}
=== Usages ===
array_filter(array, boolean closure(key, value))=== Examples === ====Example 1==== Pulls out only the odd numbers Given the following code:
@array = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
@newArray = array_filter(@array, closure(@key, @value){
return(@value % 2 == 1);
});
msg(@newArray);

1 @array = {{function|array}}(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
2 @newArray = {{function|array_filter}}(@array, {{keyword|closure}}(@key, @value){
3 {{function|return}}(@value % 2 == 1);
4 });
5 {{function|msg}}(@newArray);
{1, 3, 5, 7, 9}====Example 2==== Pulls out only the odd numbers in an associative array Given the following code:
@array = array('one': 1, 'two': 2, 'three': 3, 'four': 4);
@newArray = array_filter(@array, closure(@key, @value){
return(@value % 2 == 1);
});
msg(@newArray);

1 @array = {{function|array}}('one': 1, 'two': 2, 'three': 3, 'four': 4);
2 @newArray = {{function|array_filter}}(@array, {{keyword|closure}}(@key, @value){
3 {{function|return}}(@value % 2 == 1);
4 });
5 {{function|msg}}(@newArray);
{one: 1, three: 3}
Find a bug in this page? Edit this page yourself, then submit a pull request. (Note this page is automatically generated from the documentation in the source code.)