Created
August 31, 2020 18:39
-
-
Save trvswgnr/a435a3db530ea68e79d0687ee3ac831f to your computer and use it in GitHub Desktop.
PHP - filter array by keys containing, not containing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Return array with only keys containing a string | |
* | |
* @param string $str String to filter keys by. | |
* @param array $arr Source array. | |
* @return array Filtered array. | |
*/ | |
function keys_containing( $str, $arr ) { | |
return array_filter( | |
$arr, | |
function( $key ) use ( $str ) { | |
return strpos( $key, $str ) !== false; | |
}, | |
ARRAY_FILTER_USE_KEY | |
); | |
} | |
/** | |
* Return array without keys containing a string | |
* | |
* @param string $str String to filter keys by. | |
* @param array $arr Source array. | |
* @return array Filtered array. | |
*/ | |
function keys_not_containing( $str, $arr ) { | |
return array_filter( | |
$arr, | |
function( $key ) use ( $str ) { | |
return strpos( $key, $str ) === false; | |
}, | |
ARRAY_FILTER_USE_KEY | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment