Array Helpers #1

Category Snippets

Date 22·06·15

Tag php array combine merge

Just some random (relevance wise) functions for array manipulations.

/**
 * Combines a new array using initial array even values
 * as keys and odd as their values
 *
 * @param    array       $initial
 * @param    callable    $key_callback      Applied on keys
 * @param    callable    $value_callback    Applied on values
 * @return   array
 */
function arrayCombineFromValues(
    array $initial,
    callable $key_callback = null,
    callable $value_callback = null
) {
    $values = array_values($initial);
    $combined = array();
    for ($i = 0; $i < count($values); $i += 2) {
        $key = $key_callback ? $key_callback($values[$i]) : $values[$i];
        $val = isset($values[$i + 1]) ? $values[$i + 1] : null;
        $val = $value_callback ? $value_callback($val) : $val;
        $combined[$key] = $val;
    }
    return $combined;
}

/**
 * Merges two arrays using a callback to resolve key conflicts
 *
 * During a key conflict the callback takes the value from the first
 * array as its first param and the value from the second array as
 * the second param and should return a truthy value in case the second
 * param should take the priority over the first one
 *
 * @param   array       $first
 * @param   array       $second
 * @param   callable    $comparator    Expected to take 2 params
 * @return  array
 */
function arrayMergeCompare(
    array $first,
    array $second,
    callable $comparator
) {
    foreach ($second as $key => $val) {
        if (!isset($first[$key]) or $comparator($first[$key], $val)) {
            $first[$key] = $val;
        }
    }
    return $first;
}