Skip to content

Instantly share code, notes, and snippets.

@over-engineer
Last active November 25, 2018 23:56
Show Gist options
  • Save over-engineer/f486e41bcaa09fc3654d81b5da962bbf to your computer and use it in GitHub Desktop.
Save over-engineer/f486e41bcaa09fc3654d81b5da962bbf to your computer and use it in GitHub Desktop.
PHP equivalent of JavaScript's Array.prototype.every()
<?php
/**
* Checks if all items in array pass a test (provided as a function)
*
* If it finds an array item where the function returns a `false` value,
* it returns `false` (and does not check the remaining values)
*
* If no false occur, it returns `true`
*
* It doesn't execute the function for array elements without values
* It doesn't change the original array
*
* Based on JavaScript `Array.prototype.every()`
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every
*
* @param array $arr The array to check its items
* @param array|string $test_func The name of the test function
* @return boolean Whether all items in the given
* array passed the test or not
*/
public static function every( $arr, $test_func ) {
foreach ( $arr as $item ) {
if ( !call_user_func( $test_func, $item ) ) {
return false;
}
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment