Skip to content

Instantly share code, notes, and snippets.

@eatonphil
Last active August 29, 2015 14:14
Show Gist options
  • Save eatonphil/6de8b6c688c72408e44f to your computer and use it in GitHub Desktop.
Save eatonphil/6de8b6c688c72408e44f to your computer and use it in GitHub Desktop.
<?php
/**
* Original Source: http://www.gerbenjacobs.nl/push-new-value-into-array-with-php/
*/
function array_push_insert($array, $index, $value) {
if (array_key_exists($index, $array)) {
$firstArray = array_slice($array, 0, $index);
$lastArray = array_slice($array, $index);
array_push($firstArray, $value);
$array = array_merge($firstArray, $lastArray);
} else {
$array[key] = $value;
}
return $array;
}
function partial($f, $p, $v) {
$_f = new ReflectionFunction($f);
$params = array();
foreach ($_f->getParameters() as $param) {
$params[] = $param->name;
}
$i = array_search($p, $params);
return function() use ($_f, $i, $v) {
$args = func_get_args();
$args = array_push_insert($args, $i, $v);
return $_f->invokeArgs($args);
};
}
function t($a, $b, $c) {
return $a + (2*$b) + (3*$c);
}
$t_p = partial(t, 'a', 7);
$res = $t_p(1, 3);
echo $res . "\n"; // 18
$t_p = partial(t, 'b', 7);
$res = $t_p(1, 3);
echo $res . "\n"; // 24
$t_p = partial(t, 'c', 7);
$res = $t_p(1, 3);
echo $res . "\n"; // 28
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment