Skip to content

Instantly share code, notes, and snippets.

@bmoredrew
Created September 6, 2017 21:12
Show Gist options
  • Save bmoredrew/baeb076668ee739708a95c153dd0e5f6 to your computer and use it in GitHub Desktop.
Save bmoredrew/baeb076668ee739708a95c153dd0e5f6 to your computer and use it in GitHub Desktop.
PHP: Array support class and functions
<?php
/**
* Support class for working with arrays.
*/
class Arr
{
/**
* Extend an associative array.
*
* Values in $option array overwrite those in $default, but only for keys
* which are present in $default. All other keys are discarded.
*
* @access public
*
* @param array $default
* @param array $options
* @return array
*/
public static function extend( array $default, array $options ) : array
{
return array_intersect_key( array_merge( $default, $options ), $default );
}
/**
* Pluck values from a collection of arrays or objects.
*
* @access public
*
* @param array $array
* @param string $key
* @return array
*/
public static function pluck( array $collection, string $key ) : array
{
return array_map( function( $v ) use ( $key ) {
return is_object( $v ) ? $v->$key : $v[ $key ];
}, $collection );
}
/**
* Trim whitespace from all values, optionally removing empty ones.
*
* @access public
*
* @param array $arr
* @param bool $filter_empty Whether to unset empty values
* @return array
*/
public static function trim( array $array, $filter_empty = false ) : array
{
$array = array_map( 'trim', $array );
return ( $filter_empty ) ? array_filter( $array ) : $array;
}
}
<?php
/**
* Helper function for working with arrays.
*/
require "Arr.php";
/**
* Extend an associative array.
*
* Values in $option array overwrite those in $default, but only for keys
* which are present in $default. All other keys are discarded.
*
* @param array $default
* @param array $options
* @return array
*/
if ( ! function_exists( 'array_extend' ) ) :
function array_extend( array $default, array $options ) : array {
return Arr::extend( $default, $options );
}
endif;
/**
* Pluck values from a collection of arrays or objects.
*
* @param array $array
* @param string $key
* @return array
*/
if ( ! function_exists( 'array_pluck' ) ) :
function array_pluck( array $collection, string $key ) : array {
return Arr::pluck( $collection, $key );
}
endif;
/**
* Trim whitespace from all values, optionally removing empty ones.
*
* @param array $arr
* @param bool $filter_empty Whether to unset empty values
* @return array
*/
if ( ! function_exists( 'array_trim' ) ) :
function array_trim( array $array, $filter_empty = false ) : array {
return Arr::trim( $array, $filter_empty );
}
endif;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment